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

时间:2015-02-03 13:07:02

标签: sql sql-server

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        

2 个答案:

答案 0 :(得分:2)

语法说你正在使用MSSQL。使用Recursive CTE生成calender表,然后使用Left outer join表格执行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) 

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

答案 1 :(得分:0)

这将使用构建表来创建日历:

;WITH limits as
(
  SELECT min([CreatedOn]) mi, max([CreatedOn]) ma 
  FROM xxx
), months as(
  SELECT 
    dateadd(mm, number, mi) m
  FROM
    master..spt_values v
  JOIN
    limits l
  ON 
    number between 0 and datediff(mm, l.mi, l.ma) 
  WHERE 
    v.type = 'P'
)
SELECT 
  year(months.m) year, 
  month(months.m) month,
  count(qry.[CreatedOn]) cnt
FROM
  xxx qry 
RIGHT JOIN
  months
ON
  months.m = dateadd(mm, datediff(mm, 0, qry.[CreatedOn]), 0)
GROUP BY
  year(months.m), 
  month(months.m)