这是一个真正的脑筋急转弯。
我想要一个优雅的解决方案,以简化重叠的时间段,但要注意的是,尽管某些时间段重叠,但它们不一定在它们之间形成连续的历史记录。对于具有多个协议的客户,以以下数据为例,我想确定一个日期历史记录,以标识该客户拥有有效协议的时间段(99999999是用于标识仍处于活动状态的密钥):
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
给出结果:
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
所需结果:
CustomerKey ContractStartDateKey ContractEndDateKey
1 20170120 20170819
2 20160105 99999999
34 20140103 20150303
34 20150430 99999999
56 20130406 20141106
任何曾经处理过此类问题的人的任何提示都将是很棒的。数据的大小足够小,如果需要,可以允许循环。