计算两个日期之间的日期的记录计数
要计算多轴图表的日期范围内的记录数,我们必须克服原始查询中操作数类型不匹配的问题。为了解决这个问题,我们探索利用统计表或函数的替代方法。
一种高性能的解决方案涉及利用统计表或函数。 Itzik Ben-Gan 著名的计数函数可以按如下方式合并:
DECLARE @StartDate date = '2020-11-01', @EndDate date = '2021-02-22'; WITH L0 AS ( SELECT 1 AS c FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1), (1),(1),(1),(1),(1),(1),(1),(1)) AS D(c) ), L1 AS ( SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B ), L2 AS ( SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B ), Nums AS ( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum FROM L2 ) Date_Range_T (d_range) AS ( SELECT TOP(DATEDIFF(day, @StartDate, @EndDate) + 1) DATEADD(day, rownum - 1, @StartDate) AS d_range, DATEADD(day, rownum, @StartDate) AS d_rangeNext FROM Nums ) SELECT d_range, COUNT(Id) AS Total FROM Date_Range_T LEFT JOIN tbl_Support_Requests R ON R.CreatedDate >= T.d_range AND R.CreatedDate < T.d_rangeNext GROUP BY d_range ORDER BY d_range ASC
此方法生成指定时间段的日期范围表,然后在与 tbl_Support_Requests 表的左连接中使用该表来对其中的记录进行计数每个日期范围。
以上是如何在SQL中高效统计某个日期范围内的记录?的详细内容。更多信息请关注PHP中文网其他相关文章!