我有ShiftMaster表,每台机器分配开始时间和结束时间,机器可以多班。有一些工作是在机器上进行。
即ShiftMaster,例如
MachineID SHIFTID STIME ETIME
A110T02 1 07:00:00.0000000 16:00:00.0000000
A110T02 2 14:00:00.0000000 23:00:00.0000000
A110T02 3 23:00:00.0000000 07:00:00.0000000
如果我通过机器名称,开始作业日期时间和结束作业时间,它应该重新调整班次开始时间和结束时间。
我面临第三班的问题,因为它涉及半夜时间,即两天
我期待提供这样的输入
@machineName = 'A110T02'
@startJobdatetime = '2015-12-01 23:02:00'
@EndJobdatetime = '2015-12-01 23:20:00'
结果应该返回
3 23:00:00.0000000 07:00:00.0000000
中给出了正确的格式答案 0 :(得分:0)
这应该有效:
declare @machineName varchar(50) = 'A110T02'
declare @startJobdatetime datetime = '2015-12-01 23:02:00'
declare @EndJobdatetime datetime = '2015-12-01 23:20:00'
SELECT *
FROM @ShiftMaster
WHERE MachineID = @machineName
AND CAST(DATEADD(hour, -7, @startJobdatetime) as time) >= DATEADD(hour, -7, STIME)
AND CAST(DATEADD(hour, -7, @EndJobdatetime) as time) <= DATEADD(NANOSECOND, -100, DATEADD(hour, -7, ETIME))
<强>输出:强>
MachineID SHIFTID STIME ETIME
A110T02 3 23:00:00.0000000 07:00:00.0000000
数据:强>
declare @ShiftMaster table(MachineID varchar(50), SHIFTID int , STIME time, ETIME time)
INSERT INTO @ShiftMaster(MachineID, SHIFTID, STIME, ETIME) values
('A110T02', 1, '07:00:00.0000000', '16:00:00.0000000')
, ('A110T02', 2, '14:00:00.0000000', '23:00:00.0000000')
, ('A110T02', 3, '23:00:00.0000000', '07:00:00.0000000')
答案 1 :(得分:0)
试
DECLARE @Tmp table (MachineID VARCHAR(20),SHIFTID INT,STIME VARCHAR(25),ETIME VARCHAR(25))
INSERT @Tmp SELECT 'A110T02',1,'07:00:00.0000000','16:00:00.0000000'
INSERT @Tmp SELECT 'A110T02',2,'14:00:00.0000000','23:00:00.0000000'
INSERT @Tmp SELECT 'A110T02',3,'23:00:00.0000000','07:00:00.0000000'
DECLARE @machineName VARCHAR(20) = 'A110T02'
,@startJobdatetime VARCHAR(25) = '2015-12-01 23:02:00'
,@EndJobdatetime VARCHAR(25) = '2015-12-01 23:20:00'
,@ShiftId INT = 3
;with t11 as
(select MachineID,SHIFTID,
cast(CAST(left(@startJobdatetime,10) AS datetime)+cast(stime as time) as datetime) as st,
cast(cast(left(@startJobdatetime,10) AS datetime)+cast(ETIME as time) as datetime) et
from @tmp where cast(etime as time)>cast(stime as time)
union all
select MachineID,SHIFTID,
cast(CAST(left(@startJobdatetime,10) AS datetime)+cast(stime as time) as datetime),
cast(CAST(left(@startJobdatetime,10) AS datetime)+cast('23:59:59.999' as time) as datetime)
from @Tmp where cast(etime as time)<cast(stime as time)
union all
select MachineID,SHIFTID,
CAST(left(@startJobdatetime,10) AS datetime),
cast(cast(left(@startJobdatetime,10) as datetime)+cast(ETIME as time) as datetime) from @Tmp
where cast(etime as time)<cast(stime as time)
)
select t.MachineID,t.SHIFTID,t.STIME,t.ETIME from t11 join @Tmp t on t.MachineID=t11.MachineID and t.SHIFTID=t11.SHIFTID
where t11.MachineID = @machineName and st<=cast(@startJobdatetime as datetime) and et>=cast(@EndJobdatetime as datetime)