我正在使用 CTE 生成一系列日期。
12/02/2010 10:00:00 12/02/2010 10:59:59
12/02/2010 11:00:00 12/02/2010 11:59:59
12/02/2010 12:00:00 12/02/2010 12:59:59
然后,我将其加入到包含大量日期的索引视图中。
我有 2 个选项可以在日期范围之间进行计数
1)我会 SUM(case) 测试 log_date 以测试它是否在开始日期和结束日期之间,+ 1 为真,0 为假 - 所以如果没有结果,我总是会得到 '0'
12/02/2010 10:00:00 12/02/2010 10:59:59 0
12/02/2010 11:00:00 12/02/2010 11:59:59 1
12/02/2010 12:00:00 12/02/2010 12:59:59 0
2)我可以在每个日期范围内使用 WHERE 子句来计算(*)。
12/02/2010 11:00:00 12/02/2010 11:59:59 1
正如您所期望的那样 1) 是有效的,但对性能有很大的开销 2) 效率可能提高 8000%,但是如果应用了在指定日期范围之间返回空结果的过滤器,则无法返回范围。
有没有办法使用有效的 WHERE 子句但保留详细说明“0”的日期范围行?
这是案例解决方案的一些SQL:
SELECT [LABEL], [Display Start Date], [Display End Date],
SUM(CASE WHEN ([LOG].line_date BETWEEN [Start Date] AND [End Date]) THEN 1 ELSE 0 END) AS [Total Calls],
SUM(CASE WHEN ([LOG].line_date BETWEEN [Start Date] AND [End Date]) AND ([LOG].line_result = 1) THEN 1 ELSE 0 END) AS [1 Calls],
FROM [DATE RANGE FUNCTION] LEFT JOIN
dbo.vCallLog WITH (noexpand) as [LOG] on 0 > -1
GROUP BY [Start Date], [End Date], [Display Start Date], [Display End Date], [LABEL]
这是 WHERE 解决方案的一些 SQL:
SELECT [LABEL], [Display Start Date], [Display End Date],
COUNT(dbo.vCallLog.line_id) AS [Total Calls],
SUM(CASE WHEN ([LOG].line_result = 1) THEN 1 ELSE 0 END) AS [1 Calls],
FROM [DATE RANGE FUNCTION] LEFT JOIN
dbo.vCallLog WITH (noexpand) as [LOG] on 0> -1
WHERE ([LOG].line_date BETWEEN [Start Date] AND [End Date])
GROUP BY [Start Date], [End Date], [Display Start Date], [Display End Date], [LABEL]