如果表中没有该月/年的记录,如何显示月份和年份的“o”值

时间:2012-12-06 05:45:00

标签: sql sql-server

  

可能重复:
  SQL Group and Sum By Month - Default to Zero

在我的表格中,我没有几个月和一年的记录,因此我需要将“0”记录为该记录,并且需要显示从“2006”到“2012”的所有月份和年份,请建议我

提前致谢

1 个答案:

答案 0 :(得分:0)

假是你真正的桌子......

WITH DummyDates (Date) AS (
    SELECT DATEADD(DAY, DATEDIFF(DAY, 0, '20121231') - DATEDIFF(DAY, '20060101', '20121231'), 0)
        UNION ALL SELECT DATEADD(DAY, 1, Date)
            FROM DummyDates
            WHERE DATEADD(DAY, 1, Date) <= '20121231')
SELECT DatePart(yy,DummyDates.Date) as [Year],DATEPART(MM,DummyDates.Date) as [Month],SUM(Case when dummy.date is null then 0 else 1 end) as cnt
FROM DummyDates 
LEFT Join dummy on dummy.Date=DummyDates.Date
Group by DatePart(yy,DummyDates.Date),DATEPART(MM,DummyDates.Date)
Order by DatePart(yy,DummyDates.Date),DATEPART(MM,DummyDates.Date)
OPTION (MAXRECURSION 0)