2

Possible Duplicate:
generate days from date range

Here is my query:

SELECT SUM(number) AS number, c_date 
    FROM my_table 
    WHERE c_date between '11/6/2012' AND '11/12/2012' 
    GROUP BY c_date 
    ORDER BY c_date DESC

It will return something like this

11    '11/12/2012'
9     '11/9/2012'
10    '11/8/2012'
10    '11/7/2012'
10    '11/6/2012'

Now how can I force the return results to include 11/11 and 11/10 with 0 for the number rather than skipping over them entirely. Also I cannot create a date table to store the dates.

Community
  • 1
  • 1
kqlambert
  • 2,693
  • 6
  • 33
  • 50

2 Answers2

0

Since you can't create a new table, an alternate approach is to build up a "calendar" CTE.

Next, perform a LEFT JOIN from your newly created "calendar" table to my_table:

SELECT ISNULL(SUM(mt.number), 0) AS number, mc.c_date 
FROM 
    my_calendar mc LEFT JOIN
    my_table mt ON mt.c_date = mc.c_date
WHERE mc.c_date between '11/6/2012' AND '11/12/2012' 
GROUP BY mc.c_date 
ORDER BY mc.c_date DESC
Michael Fredrickson
  • 36,839
  • 5
  • 92
  • 109
0

You could create a user defined function that returns a date range. It would look like this:

CREATE FUNCTION uspDateRange(@MinDate datetime, @Maxdate datetime)
RETURNS @DateRange TABLE ([Date] datetime)
AS
BEGIN
    DECLARE @Date datetime

    SET @Date = @MinDate

    WHILE (@Date < @MaxDate)
    BEGIN
        INSERT INTO @DateRange VALUES(@Date)
        SET @Date = DATEADD(day, 1, @Date)
    END

    RETURN
END
GO

Now you can select a range to get the range of all days of October 2012:

SELECT * FROM uspDateRange('2012-10-01', '2013-11-01')

Your query would look like this:

SELECT SUM(number) AS number, c_date 
    FROM my_table t
    INNER JOIN uspDateRange('11/6/2012', '11/12/2012') r ON t.c_date = r.[Date]
    GROUP BY c_date     
    ORDER BY c_date DESC
Elian Ebbing
  • 18,779
  • 5
  • 48
  • 56