我正在使用SQL Server 2008,我想知道一种方法来返回按日期时间范围分组的事件数。开始和结束之间的间隔始终是一天。
例如,查询应返回类似于:
的内容2014-07-01 15:00:00 | 2014-07-02 15:00:00 | 23
2014-07-02 15:00:00 | 2014-07-03 15:00:00 | 32
2014-07-03 15:00:00 | 2014-07-04 15:00:00 | 2123
2014-07-04 15:00:00 | 2014-07-05 15:00:00 | 231
它可能只显示结果集中的一个日期列,但它的逻辑相同。
韩国社交协会,
答案 0 :(得分:2)
有趣的问题!
我假设您在表格中有一个日期/时间,并希望提供开始和结束日期/时间值作为参数。我现在无法针对SQL Server进行编译,但是这样的事情应该可行:
SELECT DATEDIFF (day, start_date, event_time) as period,
COUNT (event_time) as event_count
WHERE event_time >= @start_time
AND event_time <= @end_time
GROUP BY DATEDIFF (day, @start_time, event_time)
如果要显示每个句点的开始和结束时间,请通过将DATEDIFF值添加到@start_time和@end_time来在select语句中创建新的计算列。
答案 1 :(得分:1)
如果列中有event_time
,则可以确定其下降的时间间隔,并查找每个时间间隔内的事件数,如下所示:
逻辑是,如果小时是> = 15(从15:00:00开始),则start_time将是同一天。对于15:00:00之前的event_time
s,start_time将是前一天。同样,如果小时是> = 15(从15:00:00开始),则end_time将是第二天。对于15:00:00之前的event_time
s,end_time将是当天。
select
CASE
when DATEPART(hh, event_time) >= 15 then DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME))
else DATEADD(DAY, -1, DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME)))
END START_TIME,
CASE
when DATEPART(hh, event_time) >= 15 then DATEADD(DAY, 1, DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME)))
else DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME))
END END_TIME,
count(*) no_of_events
FROM events e
group by
CASE
when DATEPART(hh, event_time) >= 15 then DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME))
else DATEADD(DAY, -1, DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME)))
END,
CASE
when DATEPART(hh, event_time) >= 15 then DATEADD(DAY, 1, DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME)))
else DATEADD(HOUR, 15, CAST(CAST(event_time AS DATE) AS DATETIME))
END;
<强>参考强>: