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

问题描述 投票:1回答:1

此查询统计我们一个月内生产的瓶子数量,并按天分组。如果当天没有生产任何瓶子,则从输出中跳过,而不是返回0个瓶子。如果没有生产瓶子,如何返回当天的时间戳?我听说日历表必须用于此目的。

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
sql sql-server reporting-services sql-server-ce
1个回答
1
投票

您需要生成日期。一个非常简单的方法使用递归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;

注意:

  • 如果您有日历或理货表格,请改用它。
  • 如果日期数超过100,则需要添加OPTION (MAXRECURSION 0)
  • COUNT(bottles)看起来可疑。您真的打算SUM(bottles)吗?
  • 将列转换为date然后转换为datetime也是可疑的。目前尚不清楚为什么要在第一列使用datetime
© www.soinside.com 2019 - 2024. All rights reserved.