从SQL查询添加缺失的日期

时间:2018-10-22 20:57:04

标签: sql database

我正在尝试向查询中添加缺少的日期,以使结果如下所示:

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

而不是:

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

我希望列出过去300天,即使输出值为0。

这是我的查询:

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

1 个答案:

答案 0 :(得分:1)

您可以使用递归CTE生成数据:

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);