在执行GROUP BY时插入缺少的条目?

时间:2011-08-04 23:05:49

标签: sql sql-server sql-server-2008

我正在尝试在我的桌子上使用GROUP BY根据周数对我的参赛作品进行分组。但是,如果某一周没有条目,我如何插入0而不是缺少条目?

CREATE TABLE #TEMP (startdate datetime)

INSERT INTO #TEMP VALUES('2011-02-01')
INSERT INTO #TEMP VALUES('2011-02-02')
INSERT INTO #TEMP VALUES('2011-02-03')
INSERT INTO #TEMP VALUES('2011-02-04')
INSERT INTO #TEMP VALUES('2011-02-05')
INSERT INTO #TEMP VALUES('2011-02-18')
INSERT INTO #TEMP VALUES('2011-02-19')
INSERT INTO #TEMP VALUES('2011-02-20')
INSERT INTO #TEMP VALUES('2011-02-21')

SELECT DATEPART(YEAR,startdate) AS 'AYear',
       DATEPART(wk,startdate) AS 'AWeek',
       COUNT(*)
FROM #TEMP
GROUP BY DATEPART(YEAR,startdate),DATEPART(wk,startdate)
ORDER BY 1,2

DROP TABLE #TEMP

我得到了:

AYear   AWeek   (No column name)
2011        6       5
2011        8       2
2011        9       2

但我想要这个:

AYear   AWeek   (No column name)
2011        6       5
2011        7       0
2011        8       2
2011        9       2

有关如何执行此操作的任何建议吗?

1 个答案:

答案 0 :(得分:4)

您可以生成一个包含所有可能周/年的表格,然后执行以下操作:

SELECT fw.Year AS 'AYear',
       fk.Week AS 'AWeek',
       SUM(CASE WHEN t.startdate is not null then 1 ELSE 0 END)
FROM FakeWeeks fw
LEFT OUTER JOIN #TEMP t ON DATEPART(YEAR,startdate) = fw.year AND DATEPART(wk,startdate) = fw.week
GROUP BY DATEPART(YEAR,startdate),DATEPART(wk,startdate)
ORDER BY 1,2

或者,如果你感觉很经济,可以生成两张桌子,一张带有年份,一张带有1-52,并加入两张桌子。