This is a real brainteaser.
I want an elegant solution which simplifies overlapping time periods, the catch is that whilst some periods overlap, they do not necessarily form a continuous history between them. Take the below data for a Customer with multiple agreements, I want to identify a date history identifying the periods where the Customer had an active agreement (99999999 is a key used to identify something still active):
if object_id('tempdb..#t1') is not null
drop table #t1
create table #t1 (CustomerKey int , ContractStartDateKey int, ContractEndDateKey int)
insert into #t1 (CustomerKey,ContractStartDateKey,ContractEndDateKey)
select 34, 20140103, 20150303
union
select 34, 20141121, 20150302
union
select 34, 20150430, 20161010
union
select 34, 20150901, 20161010
union
select 34, 20151113, 20161010
union
select 34, 20160713, 99999999
union
select 34, 20180202, 99999999
union
select 1, 20170120, 20170819
union
select 2, 20160105, 99999999
union
select 56, 20130406, 20140506
union
select 56, 20130806, 20141106
Gives results:
CustomerKey ContractStartDateKey ContractEndDateKey
1 20170120 20170819
2 20160105 99999999
34 20140103 20150303
34 20141121 20150302
34 20150430 20161010
34 20150901 20161010
34 20151113 20161010
34 20160713 99999999
34 20180202 99999999
56 20130406 20140506
56 20130806 20141106
Desired outcome:
CustomerKey ContractStartDateKey ContractEndDateKey
1 20170120 20170819
2 20160105 99999999
34 20140103 20150303
34 20150430 99999999
56 20130406 20141106
Any tips from anyone who had handled this sort thing before would be great. Size of data is small enough to permit loops if needed.