在我的表格中,我没有几个月和一年的记录,因此我需要将“0”记录为该记录,并且需要显示从“2006”到“2012”的所有月份和年份,请建议我
提前致谢
答案 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)