0

I am trying to add missing dates to my query so that my results look like this:

10/22/2018 15
10/21/2018 0
10/20/2018 14

Rather than this:

10/22/2018 15
10/20/2018 14

I want the past 300 days listed, even if the output value is 0.

Here is my query:

SELECT TOP (300)
    CAST(createddate as DATE),
    count(DISTINCT ID)
FROM table
GROUP BY CAST(createddate as DATE)
ORDER BY CAST(createddate as DATE) DESC
3
  • If you got a calendar table, it's a simple Left Join to it. Commented Oct 22, 2018 at 20:59
  • Tag your question with the database you are using, please. Commented Oct 22, 2018 at 21:53
  • I am using a MS SQL database. There is no calendar table. Commented Oct 22, 2018 at 22:35

1 Answer 1

1

You can use a recursive CTE to generate the data:

WITH dates as (
      SELECT MAX(CAST(createddate as date)) as dte, 1 as lev
      FROM table
      UNION ALL
      SELECT DATEADD(day, -1, dte), lev + 1
      FROM dates
      WHERE lev < 300
     )
SELECT COUNT(DISTINCT t.ID)
FROM dates d LEFT JOIN
     table t
     ON d.dte = CAST(t.createddate as DATE)
GROUP BY d.dte
ORDER BY d.dte DESC
OPTION (MAXRECURSION 0);
Sign up to request clarification or add additional context in comments.

1 Comment

"""Query execution failed Reason: SQL Error [208] [S0002]: Invalid object name 'CTE'."""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.