您可以嘗試查找每個員工的連續時間段。下面是設置示例腳本:
declare @From datetime = '20170911'
declare @PayrollSegment table(ReportDate datetime, StartTime datetime, EndTime datetime, EmployeeKey varchar(10))
insert into @PayrollSegment(ReportDate, StartTime, EndTime, EmployeeKey) values
('20170912', '20170912', '20170912', 'Acton'),
('20170913', '20170913', '20170913', 'Acton'),
('20170914', '20170914', '20170914', 'Acton'),
('20170915', '20170915', '20170915', 'Acton'),
('20170918', '20170918', '20170918', 'Acton'),
('20170919', '20170919', '20170919', 'Acton'),
('20170920', '20170920', '20170920', 'Acton'),
('20170921', '20170921', '20170921', 'Acton'),
('20170922', '20170922', '20170922', 'Acton'),
('20170923', '20170923', '20170923', 'Acton'),
('20170924', '20170924', '20170924', 'Acton'),
('20170925', '20170925', '20170925', 'Acton'),
('20170926', '20170926', '20170926', 'Acton'),
('20170912', '20170912', '20170912', 'Ahn'),
('20170913', '20170913', '20170913', 'Ahn'),
('20170914', '20170914', '20170914', 'Ahn'),
('20170915', '20170915', '20170915', 'Ahn')
首先找到所有周期開始(即沒有用於ReportDate沒有記錄 - 1該員工):
select
ReportDate as PeriodStart
from @PayrollSegment ps
where ps.ReportDate >= @From and not exists(select 1 from @PayrollSegment ps2 where ps.EmployeeKey = ps2.EmployeeKey and ps2.ReportDate = DATEADD(day, -1, ps.ReportDate))
然後向該查詢添加相應的期末(即最小ReportDate當前操作後,對於同一名員工,針對其存在的ReportDate + 1沒有記錄):
select
ReportDate as PeriodStart
, (select min(ps3.ReportDate) from @PayrollSegment ps3 where ps3.ReportDate > ps.ReportDate and not exists(select 1 from @PayrollSegment ps4 where ps4.EmployeeKey = ps3.EmployeeKey and ps4.ReportDate = DATEADD(day, 1, ps3.ReportDate))) as PeriodEnd
from @PayrollSegment ps
where ps.ReportDate >= @From and not exists(select 1 from @PayrollSegment ps2 where ps.EmployeeKey = ps2.EmployeeKey and ps2.ReportDate = DATEADD(day, -1, ps.ReportDate))
這給你連續幾天的列表。只要選擇那些至少7天長的期間:
; with cte as (
select
ReportDate as PeriodStart
, (select min(ps3.ReportDate) from @PayrollSegment ps3 where ps3.ReportDate > ps.ReportDate and not exists(select 1 from @PayrollSegment ps4 where ps4.EmployeeKey = ps3.EmployeeKey and ps4.ReportDate = DATEADD(day, 1, ps3.ReportDate))) as PeriodEnd
from @PayrollSegment ps
where ps.ReportDate >= @From and not exists(select 1 from @PayrollSegment ps2 where ps.EmployeeKey = ps2.EmployeeKey and ps2.ReportDate = DATEADD(day, -1, ps.ReportDate))
)
select * from cte where DATEDIFF(day, PeriodStart, PeriodEnd) >= 7
完美,謝謝! –