请你看看下面的任务吗?
我有' SCHEDULE'表。它具有以下结构:
CREATE TABLE SCHEDULE (
EMPLOYEE nvarchar(50),
SHIFT_START datetime,
SHIFT_END datetime
)
'附表'包含数据:
INSERT INTO SCHEDULE(EMPLOYEE,SHIFT_START,SHIFT_END) VALUES
('EMP01','2017-08-21 09:00:00.000','2017-08-21 12:00:00.000'),
('EMP01','2017-08-21 12:30:00.000','2017-08-21 16:00:00.000'),
('EMP01','2017-08-21 17:00:00.000','2017-08-21 20:00:00.000'),
('EMP02','2017-08-21 09:00:00.000','2017-08-21 12:00:00.000'),
('EMP02','2017-08-21 13:30:00.000','2017-08-21 16:00:00.000'),
('EMP02','2017-08-21 16:30:00.000','2017-08-21 20:00:00.000'),
('EMP03','2017-08-21 09:00:00.000','2017-08-21 12:00:00.000'),
('EMP03','2017-08-21 15:30:00.000','2017-08-21 20:00:00.000')
任务:如果每个员工的每个日期的班次开始日期和上一个班次结束日期之间的差异大于1分钟且小于60分钟 - 而不是再添加一行(&# 39;打破现有数据集。
提前谢谢!
答案 0 :(得分:3)
您需要以前的值。在SQL Server 2008中,一种方法使用apply
。要获得其他行:
select employee, prev_shift_end, shift_start, 'break' as shift_type
from (select s.*, sprev.shift_end as prev_shift_end
from schedule s cross apply
(select top 1 s2.*
from schedule s2
where s2.employee = s.employee and
s2.shift_start < s.shift_start
order by s2.shift_start desc
) sprev
) s
where datediff(minute, prev_shift_end, shift_start) between 1 and 60;
您可以在逻辑之前放置insert
以在表中插入行。