計算兩個日期之間的日期的記錄計數
要計算多軸圖表的日期範圍內的記錄數,我們必須克服原始查詢中操作數類型不符的問題。為了解決這個問題,我們探索利用統計表或函數的替代方法。
一種高效能的解決方案涉及利用統計表或函數。 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中文網其他相關文章!