从下表中,我需要获得EndTime在20:00到00:00之间的访问。 (以黄色突出显示)
这是我现在使用的查询,但如果我没有得到任何结果。如果我将时间00:00更改为23:59,我将得到另外两个结果,但不是结束时间= 00:00的结果。
Select VisitID, StartTime, duration, dateadd(minute,Duration,StartTime) as EndTime
from visit
where StartTime between '2018-02-01' and '2018-02-02 23:59'
and cast(dateadd(minute,Duration,StartTime) as Time) >= '20:00'
and cast(dateadd(minute,Duration,StartTime) as Time) <= '00:00'
请协助。感谢。
答案 0 :(得分:1)
由于时间00:00早于20:00
,您无法获得任何结果检查20:00和23:59,OR条件为00:00
AND
(
cast(dateadd(minute,Duration,StartTime) as Time) BETWEEN '20:00' AND '23:59'
OR cast(dateadd(minute,Duration,StartTime) as Time) = '00:00'
)
答案 1 :(得分:1)
为了在两个日期之间获取数据,我不会更喜欢BETWEEN
子句。我们可以使用>=
和<=
运算符执行此操作,如下所示 -
declare @visit table (visitid uniqueidentifier, StartTime datetime, duration int)
insert into @visit
select newid(), '2018-02-01 19:00:00', 60
union all
select newid(), '2018-02-01 20:00:00', 240
union all
select newid(), '2018-02-01 21:00:00', 120
Select VisitID, StartTime, duration, dateadd(minute,Duration,StartTime) as EndTime
from @visit
where
dateadd(minute,Duration,StartTime) >= '2018-02-01 20:00:00'
and dateadd(minute,Duration,StartTime) <= '2018-02-02 00:00:00'
答案 2 :(得分:1)
我看到的唯一问题是你使用的是AND而不是OR。
Select VisitID, StartTime, duration, dateadd(minute,Duration,StartTime) as EndTime
from visit
where StartTime between '2018-02-01' and '2018-02-02 23:59'
and (cast(dateadd(minute,Duration,StartTime) as Time) >= '20:00'
or cast(dateadd(minute,Duration,StartTime) as Time) <= '00:00')