SQL 计算每日总计跳过天数的查询

SQL Query to Count Daily Totals Skips Days

此查询计算我们在一个月内生产的瓶子数量,并按天对它们进行分组。如果那天没有瓶子生产,那么它会从输出中跳过,而不是 returning 0 瓶生产。如果没有生产瓶子,我如何 return 使用当天的时间戳?我听说为此必须使用日历 table。

SELECT CONVERT(datetime,CAST(t_stamp AS DATE)), COUNT(bottles) AS 'Good Bottles'
FROM bottles
WHERE t_stamp
    BETWEEN "any date"
    AND "any date"
GROUP BY CAST(t_stamp AS DATE)
ORDER BY CAST(t_stamp AS DATE) ASC

当前输出:

Aug 12, 2019 12:00 am..................4302
Aug 13, 2019 12:00 am..................2302
Aug 17, 2019 12:00 am..................1302
Aug 18, 2019 12:00 am..................4302

期望的输出:

Aug 12, 2019 12:00 am..................4302
Aug 13, 2019 12:00 am..................2302
Aug 14, 2019 12:00 am..................0
Aug 15, 2019 12:00 am..................0
Aug 16, 2019 12:00 am..................0
Aug 17, 2019 12:00 am..................1302
Aug 18, 2019 12:00 am..................4302

您需要生成日期。一个非常简单的方法使用递归 CTE:

WITH dates as (
      SELECT CONVERT(date, "any date1") as dte
      UNION ALL
      SELECT DATEADD(day, 1, dte)
      FROM dates
      WHERE dte < "any date2"
     )
SELECT d.dte, COUNT(bottles) AS GoodBottles
FROM dates d LEFT JOIN
     bottles b
     ON CAST(t_stamp as DATE) = d.dte
GROUP BY d.dte
ORDER BY d.dte ASC;

备注:

  • 如果您有日历或记事本 table,请改用它。
  • 如果日期数量超过100个,需要添加OPTION (MAXRECURSION 0).
  • COUNT(bottles) 看起来很可疑。你真的打算SUM(bottles)吗?
  • 将列转换为 date,然后再转换为 datetime 也是可疑的。目前还不清楚为什么你想要 datetime 作为第一列。