Insert Missing Dates from a query
Here is an example using a calendar table (which you really should have). This example just populates 2014 but you can stuff it with as many years as you like...
CREATE TABLE dbo.Calendar(d DATE PRIMARY KEY);
INSERT dbo.Calendar(d) SELECT TOP (365)
DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY number)-1, '20140101')
FROM [master].dbo.spt_values
WHERE [type] = N'P' ORDER BY number;
Now the query is simple:
DECLARE @s DATE = '20140518', @e DATE = '20140527';
SELECT c.d, Frequency = COALESCE(s.Frequency,0)
FROM dbo.Calendar AS c
LEFT OUTER JOIN dbo.splunge AS s
ON c.d = s.[date]
WHERE c.d >= @s
AND c.d < DATEADD(DAY, 1, @e);
SQLfiddle example
If you can't create a calendar table (and don't have a numbers table handy either), then you can just put it inline:
DECLARE @s DATE = '20140518', @e DATE = '20140527';
SELECT c.d, Frequency = COALESCE(s.Frequency,0)
FROM
(
SELECT TOP (DATEDIFF(DAY, @s, @e)+1)
DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY number)-1, @s)
FROM [master].dbo.spt_values
WHERE [type] = N'P' ORDER BY number
) AS c(d)
LEFT OUTER JOIN dbo.splunge2 AS s
ON c.d = s.[date]
WHERE c.d >= @s
AND c.d < DATEADD(DAY, 1, @e);
SQLfiddle example
For more on generating sets (of dates, numbers, etc) see this series:
- http://sqlperformance.com/generate-a-set-1
- http://sqlperformance.com/generate-a-set-2
- http://sqlperformance.com/generate-a-set-3