我遇到了一个与过滤掉在特定时间间隔(即 7 到 9 点)内事件的事件相关的问题
EventId StartTime EndTime
18 2013-04-11 16:33:11.735342100 2013-04-11 17:16:47.976164100
19 2013-04-10 16:33:46.575337300 2013-04-11 18:10:08.428443900
20 2013-04-10 17:17:04.033083300 2013-04-11 18:10:13.907757900
21 2013-04-11 00:10:24.293352100 2013-04-11 18:45:17.754240800
23 2013-04-11 01:11:20.278558900 2013-04-11 18:45:00.435247300
25 2013-04-15 09:42:22.549026700 2013-04-15 23:54:33.389964300
26 2013-04-16 07:42:24.588807700 2013-04-16 17:42:41.077751300
28 2013-04-19 16:51:22.699240800 2013-04-19 18:39:03.167468100
31 2013-04-19 18:30:56.891621300 2013-04-19 19:42:50.418640200
17 2013-04-20 16:07:07.327879000 2013-04-20 22:17:17.783053600
我想过滤掉那些在上午 7 点到 9 点期间事件的事件,包括从 8 点开始的事件,我使用了简单的时间比较,它按预期工作,但给定数据集,它无法获得一些结果,例如事件 ID 20
20 2018-05-10 17:17:04.033083300 2018-05-11 18:10:13.907757900
因为此事件在第二天 7-9 点的时间间隔内有效,但由于日期更改,我无法获取它。
最佳答案
我认为这个逻辑可以检测到任何重叠:
where -- more than one day, then automatic
endTime > dateadd(day, 1, startTime) or
( -- same day
convert(date, endTime) = convert(date, startTime) and
datepart(hour, startTime) < 9 and
datepart(hour, endTime >= 7
) or
( -- next day
convert(date, endTime) = dateadd(day, 1, convert(date, startTime)) and
datepart(hour, startTime) < 9 or
datepart(hour, endTime >= 7
)
请注意,这会检测与时间段的任何重叠,而不是完全重叠。
编辑:
对于完全重叠:
where -- more than one day, then automatic
endTime > dateadd(day, 1, startTime) or
( -- same day
convert(date, endTime) = convert(date, startTime) and
convert(time, startTime) <= '07:00:00' and
convert(time, endTime) >= '09:00:00'
) or
( -- next day
convert(time, startTime) <= '07:00:00' or
convert(time, endTime) >= '09:00:00'
)
关于sql:根据给定间隔过滤日期时间列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929476/