按照要求,这是一个修改后的版本,其考虑多种PK/FK
Declare @Table1 table (PK int,Date1 Date,Date2 Date, Person varchar(25))
Insert into @Table1 values
(1,'1/1/16','7/1/16','A'),
(2,'2/1/16','8/1/16','A')
Declare @Table2 table (FK int,Date1 Date,Date2 Date, Person varchar(25))
Insert into @Table2 values
(1,'2/1/16','2/4/16','B'),
(1,'3/6/16','3/8/16','C'),
(1,'5/4/16','5/9/16','B'),
(2,'3/1/16','3/4/16','B'),
(2,'3/6/16','3/8/16','C'),
(2,'5/4/16','5/9/16','B')
;with cteBase as (
Select *
,Gap1 = Date2
,Gap2 = Lead(Date1,1,(Select max(Date2) from @Table1 Where FK=PK)) over (Partition By FK Order by Date1)
From @Table2
)
Select PK,Date1,Date2=(Select min(Date1) from @Table2 Where FK=PK),Person From @Table1
Union All
Select FK,Date1,Date2,Person from cteBase
Union All
Select FK,Date1=Gap1,Date2=Gap2,Person=B.Person
From cteBase A
Join @Table1 B on FK=PK
Where Gap1<>Gap2
Order by PK,Date1
返回
PK Date1 Date2 Person
1 2016-01-01 2016-02-01 A
1 2016-02-01 2016-02-04 B
1 2016-02-04 2016-03-06 A
1 2016-03-06 2016-03-08 C
1 2016-03-08 2016-05-04 A
1 2016-05-04 2016-05-09 B
1 2016-05-09 2016-07-01 A
2 2016-02-01 2016-03-01 A
2 2016-03-01 2016-03-04 B
2 2016-03-04 2016-03-06 A
2 2016-03-06 2016-03-08 C
2 2016-03-08 2016-05-04 A
2 2016-05-04 2016-05-09 B
2 2016-05-09 2016-08-01 A
SQL2014。所以它应该是最新的功能/等。 – Julian