如何在指定日期范围内统计行数?代码执行异常求助
问题分析与修正
核心问题
- 日期范围逻辑错误:
EventDateTime >= '2022-12-29' and EventDateTime < '2021-12-28'这个条件永远不成立,2022年的日期不可能小于2021年的日期,直接导致查询无结果。 - 若要按**日期(不含时分秒)**分组,直接用
EventDateTime分组会把同一日期不同时间的记录拆分成多个组,不符合“按日期分组”的需求。
修正后的代码
情况1:按原始datetime字段(带时分秒)分组,修正日期范围
假设你要统计2021-12-28到2021-12-29这两天的数据:
select EventDateTime, count(EventDateTime) from [dbo].[AttributionFact] where EventDateTime >= '2021-12-28' and EventDateTime < '2021-12-30' -- 左闭右开,包含28、29两天所有时间 group by EventDateTime order by EventDateTime;
情况2:按纯日期(不含时分秒)分组统计每日行数
如果需要按日期维度汇总,忽略时分秒:
select cast(EventDateTime as date) as EventDate, count(*) as RowCount from [dbo].[AttributionFact] where EventDateTime >= '2021-12-28' and EventDateTime < '2021-12-30' group by cast(EventDateTime as date) order by EventDate;
补充说明
- 用
count(*)比count(EventDateTime)更稳妥,前者统计所有行,后者会排除EventDateTime为null的行,可根据实际需求选择。 - 日期范围用左闭右开(
>= 起始日期 and < 结束日期+1)可以避免遗漏当天最后一秒的记录,也不会包含下一天的零点记录。
内容的提问来源于stack exchange,提问作者Niiru
相关产品推荐
相关产品推荐

