在SQL Server存储过程中根据时间查找正确的班次

时间:2019-04-24 07:02:25

标签: sql sql-server stored-procedures

我的表import scipy.spatial, numpy as np scipy.spatial.distance.mahalanobis([2,5], [3,6], np.linalg.inv([[.5,0],[0,2]])) # 1.5811388300841898 1.5811388300841898**2 # squared Mahalanobis distance # 2.5000000000000004 def Mahalanobis(x, covariance_matrix, mean): x, m, C = np.array(x), np.array(mean), np.array(covariance_matrix) return (x-m)@np.linalg.inv(C)@(x-m).T Mahalanobis([2,5], [[.5,0],[0,2]], [3,6]) # 2.5 np.isclose( scipy.spatial.distance.mahalanobis([2,5], [3,6], np.linalg.inv([[.5,0],[0,2]]))**2, Mahalanobis([2,5], [[.5,0],[0,2]], [3,6]) ) # True Shiftshiftstart数据类型为shiftend时,我有8个小时的班次。

time(7)

如果我在07:10执行该过程,我应该获得shift3行

ShiftNo ShiftName  ShiftStart  ShiftEnd  IsNextDay  IsBothNextDay
--------------------------------------------------------------------
   1    Shift1     7:00:00     14:59:59   0          0
   2    SHift2     15:00:00    22:59:59   0          0
   3    Shift3     23:00:00    7:00:00    1          0

我现有的程序是

23:00:00.0000000-07:00:00.0000000 as timestamp 

当我想获取班次3的行时,此过程未返回预期的输出。这种情况下的输出为空

谁能告诉我我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

转换为日期时间以进行比较。对于班次3,结束的班次成为第二天

declare @shift table
(
    shiftno     int,
    shiftstart  time(7),
    shiftend    time(7)
)

--  sample data
insert into @shift values
(1, '07:00', '14:59:59'),
(2, '15:00', '22:59:59'),
(3, '23:00', '07:00:00')

declare @Currenttime    as time

set @Currenttime = '06:30'

--  the query
; with shifts as
(
    select  *, 
        shift_start = convert(datetime, shiftstart),
        shift_end   = case  when shiftstart < shiftend
                    then convert(datetime, shiftend)
                    else dateadd(day, 1, convert(datetime, shiftend))
                    end
    from    @shift
)
select  *
from    shifts
where   convert(datetime, @Currenttime) between shift_start and shift_end
or       dateadd(day, 1, convert(datetime, @Currenttime)) between shift_start and shift_end

编辑:要基于@Currenttime获得上一个班次,请使用以下查询

--  the query
; with 
shifts as
(
    select  *, 
        shift_start = convert(datetime, shiftstart),
        shift_end   = case  when shiftstart < shiftend
                    then convert(datetime, shiftend)
                    else dateadd(day, 1, convert(datetime, shiftend))
                    end
    from    @shift
),
current_shift as
(
    select  PrevShiftTime = dateadd(minute, -1, shiftstart)
    from    shifts
    where   convert(datetime, @Currenttime) between shift_start and shift_end
    or       dateadd(day, 1, convert(datetime, @Currenttime)) between shift_start and shift_end
)
select  *
from    shifts s
    cross join current_shift c
    where   convert(datetime, PrevShiftTime) between shift_start and shift_end
    or       dateadd(day, 1, convert(datetime, PrevShiftTime)) between shift_start and shift_end