我有一个名为SHIFT的sql表,其列为:
No, Start, Duration(hours)
1, 7am, 7
2, 3pm, 7
3, 11pm, 7
如何使用sql查询知道哪个班次正在运行?
答案 0 :(得分:2)
这是一个诀窍
;WITH cte
AS (SELECT *,
Cast(Cast(start AS DATETIME) AS TIME) AS start_time,
Cast(Getdate() AS TIME) AS curr_time
FROM (VALUES (1,'7am',7),
(2,'3pm',7),
(3,'11pm',7)) tc (No, Start, Duration))
SELECT TOP 1 No,
Start,
Duration
FROM cte
WHERE Datediff(second, start_time, curr_time) >= 0
ORDER BY Datediff(second, start_time, curr_time)
将7am
转换为datetime
可为您提供1900-01-01 07:00:00.000
。
现在我们可以使用07:00:00.000
1900-01-01 07:00:00.000
中的时间部分(datetime
)与当前时间进行比较
答案 1 :(得分:0)
我建议添加计算列finish
,以便按between
运算符和<
>
create table #test
(
start time,
lag tinyint
)
insert into #test(start, lag)
values
('7am', 7),
('8am', 3),
('10pm', 13),
('11am', 6)
alter table #test add finish as (dateadd(hh, lag, start))
/* all rows with computed column */
select * from #test
/* row with period current time falls in */
select *
from #test t
where cast(getdate() as time) between t.start and t.finish
order by t.start
drop table #test