-1

我正在使用 Microsoft SQL Server 并有 2 个表,AbsenceHistory 和 FITNoteHistory。

AbsenceHistory:

[Employee Number], [Absence Number], [Start Date], [End Date]

FITNoteHistory:

[Absence Number], [FIT Note Number], [Start Date], [End Date]

我需要确定 FIT Note 历史记录中的空白处,这并没有涵盖整个Absence Period between DateAdd(d,7,AbsenceHistory.[Start Date]) and AbsenceHistory.[End Date], where AbsenceHistory.[End Date] is not null and DATEDIFF(d,AbsenceHistory.[Start Date],AbsenceHistory.[End Date]) >= 7.

输出需要给我每次缺席的实际日期间隔。

例如缺勤编号、间隔日期

任何人都可以帮忙吗?

示例数据:

AbsenceHistory:
[Employee Number], [Absence Number], [Start Date], [End Date]
18615, 70, '01-Jan-2018', '31-Jan-2018'

FITNoteHistory:
[Absence Number], [FIT Note Number], [Start Date], [End Date]
70, 1, '08-Jan-2018', '15-Jan-2018'
70, 15, '18-Jan-2018', '24-Jan-2018'
70, 31, '26-Jan-2018', '01-Feb-2018'

我的预期输出是:

[Employee Number], [Absence Number], [Gap Date]
18615, 70, '16-Jan-2018'
18615, 70, '17-Jan-2018'
18615, 70, '25-Jan-2018'
4

1 回答 1

0

这应该让你开始

declare @t table ([Absence Number] int, [FIT Note Number] int, [Start Date] date, [End Date] date) 
insert into @t values
        (70, 1,  '08-Jan-2018', '15-Jan-2018')
      , (70, 15, '18-Jan-2018', '24-Jan-2018')
      , (70, 31, '26-Jan-2018', '01-Feb-2018');
select t.[Absence Number], t.[FIT Note Number], t.[Start Date], t.[End Date]
from @t t
order by t.[Start Date], t.[End Date], t.[FIT Note Number];
declare @minDate date = (select min([End Date])   from @t);
declare @maxDate date = (select max([Start Date]) from @t);
with cteDate as
(
    select @minDate as dDate
    union all 
    select cast(dateadd(dd, 1, dDate) as date) 
    from cteDate 
    where dDate < @maxDate
)
,   cteNext as
(  select t.[Absence Number], t.[FIT Note Number], t.[Start Date], t.[End Date] 
        , lead(t.[Start Date], 1)  OVER (ORDER BY t.[Start Date]) AS nextStart
   from @t t
)
select n.[Absence Number], n.[FIT Note Number], n.[Start Date], n.[End Date] 
    ,  d.dDate  
 from cteNext n 
 join cteDate d
   on d.dDate > n.[End Date] 
  and d.dDate < n.nextStart
order by d.dDate;
于 2018-03-02T17:40:36.697 回答