如果你在一列中有
event_time
,那么你可以确定它所处的区间,并找到每个区间内的事件数,如下所示。
其逻辑是,如果小时>=15(从15:00:00开始),start_time将是同一天的。对于
event_time
,在15:00:00之前,start_time将是前一天的时间。同样地,如果小时数>=15(从15:00:00开始),结束时间将是第二天。对于
event_time
,在15:00:00之前,end_time将是当天的时间。
select
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,
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
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,
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;