使用SQL Server获取12个月的数据计数名称?

时间:2017-08-28 12:28:39

标签: sql-server

我创建了一个查询,以获得12个月的名字,并获得该月的计数。使用我的查询,我每月都会收到数据并获得月份名称。

但是在我的查询中,如果6月份的表中没有任何数据,我将无法获得6月份的参赛作品。我想要显示六月份,有0个数据。怎么办?我不知道。

这是我的问题:

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)

这是我的回复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
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月,sep,oct,nav,dec mont条目在表中不是availbale。我希望这个提醒月也可以使用0值的计数器。

2 个答案:

答案 0 :(得分:1)

使用adhoc日历表生成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

rextester演示:http://rextester.com/NNVI43016

返回:

+----+--------+-------+
| 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 |
+----+--------+-------+

这具有额外的优势,因为它不会在较大的表Comments中的列上调用函数,并且它正在使用SARGable条件进行连接。

参考:

答案 1 :(得分: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)

或者,如果您已经有time表,请改用它。