事实
- 有两个表MachineStatus和MachineShift。
- 他们通过FK:machineName。
相互链接 醇>
需要输出
根据班次获取机器状态持续时间 请查看附图以澄清输出。
问题
我无法达到旧日期状态,满足左联接条件的条件是什么? 任何帮助将不胜感激
数据库架构
DECLARE @machineStatus TABLE (id int, DateFrom DATETIME, DateTo DATETIME, mStatus int, machineName Varchar(10));
INSERT INTO @machineStatus
(id, dateFrom, DateTo, mStatus, machineName)
VALUES
(1, '2017-01-24 08:00', '2017-01-24 09:00', 1, 'MachineA'),
(2, '2017-01-24 09:00', '2017-01-24 09:30', 2, 'MachineA'),
(3, '2017-01-24 09:30', '2017-01-24 18:30', 1, 'MachineA'),
(4, '2017-01-24 18:30', '2017-01-24 21:30', 2, 'MachineA'),
(5, '2017-01-24 21:30', '2017-01-25 00:30', 3, 'MachineA')
,(6, '2017-01-25 00:30', NULL, 1, 'MachineA')
;
--SELECT * FROM @machineStatus
DECLARE @machineShift TABLE
(id int, TimeStart TIME, TimeEnd TIME, MachineName varchar(10), machineShift int);
INSERT INTO @machineShift
(id, TimeStart, TimeEnd, MachineName, machineShift)
VALUES
(1, '08:30', '20:30', 'MachineA', 1),
(2, '20:30', '08:30', 'MachineA', 2),
(3, '09:30', '21:00', 'MachineB', 1),
(4, '21:00', '08:30', 'MachineB', 2)
;
--SELECT * FROM @machineShift
查询
SELECT ms.id, ms.DateFrom, ms.DateTo, ms.mStatus, sft.machineName,
sft.machineShift,
DATEADD(DAY, DATEDIFF(DAY, '19000101', CAST(ms.DateFrom AS DATE)), CAST (sft.TimeStart AS DATETIME)
) AS ShiftStart,
DATEADD(DAY,
CASE WHEN DATEDIFF(SECOND, CAST(sft.TimeStart AS TIME), CAST(sft.TimeEnd AS TIME)) <= 0 THEN 1 ELSE 0 END,
DATEADD(DAY, DATEDIFF(DAY, '19000101', CAST(ms.DateFrom AS DATE)), CAST(sft.TimeEnd AS DATETIME))
) AS ShiftEnd
FROM @machineStatus AS ms
LEFT JOIN @machineShift AS sft
ON (ms.machineName = sft.machineName
AND ms.DateFrom >=
DATEADD(DAY, DATEDIFF(DAY, '19000101', CAST(ms.DateFrom AS DATE)), CAST(sft.TimeStart AS DATETIME))
AND ms.DateFrom <= DATEADD(DAY,
CASE WHEN DATEDIFF(SECOND, CAST(sft.TimeStart AS TIME), CAST(sft.TimeEnd AS TIME)) <= 0 THEN 1 ELSE 0 END,
DATEADD(DAY, DATEDIFF(DAY, '19000101', CAST(ms.DateFrom AS DATE)), CAST(sft.TimeEnd AS DATETIME)))
)