Sql server 使用SQL Server获取具有数据计数的12个月名称?
我创建了一个查询,用name获取12个月的数据,并获取该月的计数。使用我的查询,我得到的数据按月计算,也得到月份名称 但是在我的查询中,如果表中没有6月份的数据,我就不会得到6月份的条目。我希望也显示6月份,数据为0。你怎么能这么做?我不知道 我的问题是:Sql server 使用SQL Server获取具有数据计数的12个月名称?,sql-server,Sql Server,我创建了一个查询,用name获取12个月的数据,并获取该月的计数。使用我的查询,我得到的数据按月计算,也得到月份名称 但是在我的查询中,如果表中没有6月份的数据,我就不会得到6月份的条目。我希望也显示6月份,数据为0。你怎么能这么做?我不知道 我的问题是: DECLARE @year nvarchar(max) SELECT @year = year(getdate()) SELECT MONTH(InsertDateTime) AS m, FORMAT(InsertDa
DECLARE @year nvarchar(max)
SELECT @year = year(getdate())
SELECT
MONTH(InsertDateTime) AS m,
FORMAT(InsertDateTime, 'MMM-yy') AS Month,
COUNT(InsertDateTime) AS tally
FROM
Comments
WHERE
YEAR(InsertDateTime) = @year
GROUP BY
FORMAT(InsertDateTime, 'MMM-yy'), MONTH(InsertDateTime)
这是我的退货订单:
m | Month | tally
1 Jan-17 1
2 Feb-17 1
3 Mar-17 10
4 Apr-17 15
5 May-17 20
8 Aug-17 25
这是我的预期o/p:
m | Month | tally
1 Jan-17 1
2 Feb-17 1
3 Mar-17 10
4 Apr-17 15
5 May-17 20
6 June-17 0
7 July-17 0
8 Aug-17 25
9 Sep-17 0
10 Oct-17 0
11 Nav-17 0
12 Dec-17 0
这个返回数据是正确的,但我在这里没有返回其他月份。与6月、7月、9月、10月、资产净值、12月和10月一样,表中没有可用的条目。我想要这个月的收尾时间,tally coulmn的值也为0。要么加入一个派生表:
SELECT s.m,s.month,COALESCE(t.tally,0) as tally
FROM (SELECT 1 as m, 'Jan-17' as Month UNION ALL
SELECT 2 as m, 'Feb-17' as Month UNION ALL
...) s
LEFT JOIN (Your Query) t
ON(s.m = t.m and s.month = t.month)
或者,如果您已经有一个
时间表
则改用它。使用临时日历表生成12个月:
/* @StartDate = truncate `getdate()` to the start of the year: */
declare @StartDate datetime = dateadd(year , datediff(year , 0, getdate()), 0)
;with Months as (
select top (12)
m = row_number() over (order by number)
,[Month] = dateadd(month, row_number() over (order by number) -1, @StartDate)
, NextMonth = dateadd(month, row_number() over (order by number), @StartDate)
from master.dbo.spt_values
)
select
m.m
, Month = format(m.Month, 'MMM-yy')
, tally = count(c.InsertDateTime)
from Months m
left join Comments c
on c.InsertDateTime >= m.Month
and c.InsertDateTime < m.NextMonth
group by m.m, format(m.Month, 'MMM-yy')
order by m
这样做的另一个优点是,它不会对较大的表Comments
中的列调用函数,而是使用可搜索的条件进行连接
参考:
。请仔细检查您对代码的修改,以确认您已删除了where
子句,该子句将导致左连接
隐式成为内部连接。@Edit乐意提供帮助!您好SqlZim我需要一些帮助和解决方案,在我的选项卡中使用此查询最多可存储10万个数据,因此此查询运行时间最多需要1分钟,所以我希望在1或2秒内获得数据,所以如何才能做到这一点。我创建了缺失的索引,还显示了执行计划。
+----+--------+-------+
| m | Month | tally |
+----+--------+-------+
| 1 | Jan-17 | 3 |
| 2 | Feb-17 | 0 |
| 3 | Mar-17 | 2 |
| 4 | Apr-17 | 0 |
| 5 | May-17 | 0 |
| 6 | Jun-17 | 0 |
| 7 | Jul-17 | 0 |
| 8 | Aug-17 | 0 |
| 9 | Sep-17 | 0 |
| 10 | Oct-17 | 0 |
| 11 | Nov-17 | 0 |
| 12 | Dec-17 | 1 |
+----+--------+-------+