根据开始时间和结束时间之间的当前时间选择班次

时间:2018-09-07 08:22:01

标签: sql sql-server date datetime

我想使用当前时间开始时间结束时间

之间选择班次
ShiftID     OrgID   ShiftName   StartTime                   EndTime
13          1-1     General     1900-01-01 09:00:00.000     1900-01-01 17:00:00.000
14          1-2     Morning     1900-01-01 08:00:00.000     1900-01-01 15:00:00.000
15          1-3     Evening     1900-01-01 15:00:00.000     1900-01-01 21:00:00.000
16          1-4     Night       1900-01-01 21:00:00.000     1900-01-01 08:00:00.000

3 个答案:

答案 0 :(得分:1)

根据您的问题,您可以尝试使用CAST(CAST(GETDATE() AS TIME) AS DATETIME)将日期设置为1900-01-01,而我们只比较time值。

检查Night需要使用一些技巧,因为该值将跨越日期。

GETDATE()'00:00:00'之间的'08:00:00'时间表示截止日期。 因此我们需要为CAST(CAST(GETDATE() AS TIME) AS DATETIME)

添加一个日期
CREATE TABLE T(
   ShiftID INT,
   OrgID VARCHAR(50),
   ShiftName VARCHAR(50),
   StartTime DATETIME,
   EndTime DATETIME
);


INSERT INTO T VALUES (13,'1-1','General','1900-01-01 09:00:00.000','1900-01-01 17:00:00.000');
INSERT INTO T VALUES (14,'1-2','Morning','1900-01-01 08:00:00.000','1900-01-01 15:00:00.000');
INSERT INTO T VALUES (15,'1-3','Evening','1900-01-01 15:00:00.000','1900-01-01 21:00:00.000');
INSERT INTO T VALUES (16,'1-4','Night','1900-01-01 21:00:00.000','1900-01-01 08:00:00.000');

查询1

SELECT t1.*
FROM T t1
WHERE   
   CASE WHEN CONVERT(datetime,CONVERT(varchar(8),GETDATE(),108))  BETWEEN CONVERT(DATETIME,'00:00:00') AND CONVERT(DATETIME,'00:08:00') 
             THEN CONVERT(datetime,CONVERT(varchar(8),GETDATE(),108))  + 1
             ELSE CONVERT(datetime,CONVERT(varchar(8),GETDATE(),108)) 
   END
         BETWEEN StartTime 
   AND 
         CASE WHEN ShiftName = 'Night' 
            THEN EndTime + 1 
            ELSE EndTime
         END 

Results

| ShiftID | OrgID | ShiftName |            StartTime |              EndTime |
|---------|-------|-----------|----------------------|----------------------|
|      13 |   1-1 |   General | 1900-01-01T09:00:00Z | 1900-01-01T17:00:00Z |
|      14 |   1-2 |   Morning | 1900-01-01T08:00:00Z | 1900-01-01T15:00:00Z |

答案 1 :(得分:1)

简单的BETWEEN子句不足以处理午夜情况。您可以执行以下操作:

SELECT *
FROM shifts
CROSS APPLY (
    SELECT CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 108)) AS CurrTime
) AS ca
WHERE
    (EndTime > StartTime AND CurrTime >= StartTime AND CurrTime < EndTime) OR
    (EndTime < StartTime AND (CurrTime < EndTime OR CurrTime >= StartTime));

Updated SQL Fiddle

答案 2 :(得分:1)

假设StartTime和EndTime处于日期时间数据类型

declare @now datetime

-- this will convert current date time to 1900-01-01 + time
select @now = convert(datetime, convert(time, getdate()))

select  *
from    @shift s
where   @now >= StartTime
and     @now <  case when StartTime < EndTime 
                     then EndTime 
                     else dateadd(day, 1, EndTime) 
                     end