我的办公室里有三个班次。如何使用Sql Query获取当前运行班次的名称?
表说明如下:
Id, Name, startTime, hours
1, Shift1, 7:00 am, 8
2, Shift2, 3:00 pm, 8
3, Shift3, 11:00 pm, 8
先谢谢
答案 0 :(得分:2)
这是一个顶级的问题,所以我会给你一个顶级的答案,而不是为你编写代码,因为这样你就可以拥有解决其他问题的工具。
我会分三个阶段来处理这个问题:
startTime
和hours
列编写一个选择每个班次的结束时间的查询,即“时间Y后X小时的时间”。使用的确切函数取决于您使用的DBMS(MySQL,PostgreSQL,MS SQL Server,SQLite等),但可能会被称为date_add
。now()
,getdate()
,CURRENT_TIME
)WHERE
子句,返回时间介于两次之间的行。 (提示:BETWEEN
是SQL中的关键字。)从你知道的东西开始简单,例如“2:00在1:00到3:00之间”。将这些放在一起,您可以构建所需的查询:选择当前时间介于startTime
和计算结束时间之间的行。
答案 1 :(得分:1)
对于SQL Server,我认为:
select Id, Name, startTime, hours
from table
where
convert(time, getdate()) >= startTime
and convert(time, getdate()) < DATEADD(HH, hours, startTime)
如果 startTime
列类型为time
。
修改强>
我强烈建议将列更改为Time
如果不能发生这种情况,请考虑以下解决方案:
select convert( time, '6:00 am' )
-- result 06:00:00.0000000
select convert( time, '6:00 pm' )
-- result 18:00:00.0000000
所以:
create view MyTableView as
select
Id,
Name,
StartTime = convert( time, startTime ),
EndTime = DATEADD(HH, hours, convert( time, startTime ) ),
ShiftDuration = hours
from
MyTable
更新 24小时班次
select
Id,
Name,
StartTime,
EndTime,
ShiftDuration
from
MyTableView
where
(
( StartTime < EndTime )
and ( convert(time, getdate()) >= StartTime )
and ( convert(time, getdate()) < EndTime )
)
or
(
( StartTime >= EndTime )
and ( convert(time, getdate()) >= StartTime )
and ( convert(time, getdate()) > EndTime )
)
答案 2 :(得分:0)
您没有指定DBMS,因此这是ANSI SQL:
select *
from (
select id, name, start_time, start_time + interval '1' hour * hours as end_Time
from shifts
) t
where current_time between start_time and end_time;
SQLFiddle示例:http://sqlfiddle.com/#!15/f5428/1