试试这个查询,我使用了稍微不同的示例数据,但查询也适用于你:
;with SampleData as(
select 1 CountryCode,
1 RegionCode,
5 CountryRiskLevel,
5 RegionRiskLevel,
CONVERT(date, '2018-01-01') EffectiveDate
union all
select 1,1,5,5,CONVERT(date, '2018-01-02')
union all
select 1,1,5,5,CONVERT(date, '2018-01-03')
union all
select 1,1,5,5,CONVERT(date, '2018-01-04')
union all
select 1,1,2,2,CONVERT(date, '2018-01-05')
union all
select 1,1,5,5,CONVERT(date, '2018-01-06')
union all
select 1,1,5,5,CONVERT(date, '2018-01-07')
union all
select 1,1,5,3,CONVERT(date, '2018-01-08')
union all
select 1,1,5,5,CONVERT(date, '2018-01-09')
union all
select 1,1,5,5,CONVERT(date, '2018-01-10')
union all
select 1,1,5,5,CONVERT(date, '2018-01-11')
)
select CountryCode,
RegionCode,
CountryRiskLevel,
RegionRiskLevel,
MIN(effectiveDate) EffecticeStartDate,
case when MAX(effectiveDate) = MIN(effectiveDate) then MAX(dt) else MAX(effectiveDate) end EffectiveEndDate
from (
select *,
ROW_NUMBER() over (partition by CountryCode, RegionCode, CountryRiskLevel, RegionRiskLevel order by EffectiveDate) rn1,
ROW_NUMBER() over (order by EffectiveDate) rn2,
case when COUNT(*) over (partition by countrycode, RegionCode, CountryRiskLevel, RegionRiskLevel) = 1
then LEAD(effectivedate) over (order by effectivedate) end dt
from SampleData
) a group by CountryCode, RegionCode, CountryRiskLevel, RegionRiskLevel, rn2 - rn1