开发者

Inserting missing entries when doing a GROUP BY?

开发者 https://www.devze.com 2023-03-25 04:50 出处:网络
I am trying to use GROUP BY on my table to group my entries according to weeks. However, if there are no entries in certain week, how can I insert a 0 as opposed to a missing entry?

I am trying to use GROUP BY on my table to group my entries according to weeks. However, if there are no entries in certain week, how can I insert a 0 as opposed to a missing entry?

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(开发者_StackOverflow中文版'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

I am getting:

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

but I want this:

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

Any suggestions on how to do this?


You can generate a table with all the possible weeks/years and then do this:

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

Or, if you're feeling economical, generate two tables, one with the years and one with 1-52 and join both.

0

精彩评论

暂无评论...
验证码 换一张
取 消