I want to fill in the missing months in a SELECT statement so I was planning on joining my table with another table that contains all months. How can I generate a table of months in a light-weight fashion? For instance,
CREATE TABLE #TEMP(Timewhen DATETIME, Value INT)
INSERT INTO #TEMP VALUES('2012-02-04', 4)
INSERT INTO #TEMP VALUES('2012-02-06', 4)
INSERT INTO #TEMP VALUES('2012-02-10', 4)
INSERT INTO #TEMP VALUES('2012-04-08', 4)
INSERT INTO #TEMP VALUES('2012-04-12', 4)
SELECT YEAR(Timewhen) EventYear, MONTH(Timewhen) EventMonth, SUM(Value) Total
FROM #TEMP
GROUP BY YEAR(Timewhen), MONTH(Timewhen)
DROP TABLE #TEMP
gives me:
EventYear EventMonth Total
2012 2 12
2012 4 8
But I need:
EventYear EventMonth Total
2012 2 12
2012 3 0
2012 4 8
Or a slightly less verbose version:
Alternate solution using Calendar table:
Create a Calendar table using instructions from here.
After creating a
Calendartable, one can use the following to achieve this: