SQL:添加不同年份的缺失月份

SQL SERVER

[CreatedOn] – DATETIME

我得到这张桌子:

Year  Month  Count
2009    7     1 
2009    9     1 
2010    1     2 
2010    3     13

来自查询:

SELECT
   YEAR ([CreatedOn]) AS 'Year',
   MONTH ([CreatedOn]) AS 'Month',
   COUNT ([CreatedOn]) AS 'Count'
FROM xxx
GROUP BY YEAR ([CreatedOn]), MONTH ([CreatedOn])

我怎样才能得到这样的表(错过了几个月和0号):

Year  Month  Count
2009    7     1
2009    8     0 
2009    9     1 
2009    10    0
2009    11    0
2009    12    0
2010    1     2 
2010    2     0
2010    3     13        

最佳答案 语法说你正在使用MSSQL.使用递归CTE生成日历表,然后使用XXX表执行左外连接

DECLARE @maxdate DATE = (SELECT Max([CreatedOn])
   FROM   xxx);

WITH calender
     AS (SELECT Min([CreatedOn]) dates,
         FROM   xxx
         UNION ALL
         SELECT Dateadd(mm, 1, dates)
         FROM   cte
         WHERE  dates < @maxdate)
SELECT Year(dates)         [YEAR],
       Month(dates)        [month],
       Count ([CreatedOn]) AS 'Count'
FROM   calender a
       LEFT OUTER JOIN xxx b
                    ON Year(dates) = Year ([CreatedOn])
                       AND Month(dates) = Month ([CreatedOn])
GROUP  BY Year(dates),
          Month(dates) 

注意:而不是递归CTE创建物理日历表

点赞