0

可能重复:
SQL 组和按月求和 - 默认为零

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

提前致谢

4

1 回答 1

0

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

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)
于 2012-12-06T07:38:04.020 回答