对重复的行进行分组并计算生效日期和结束日期

时间:2018-08-09 04:23:55

标签: sql sql-server tsql group-by duplicates

根据随附的示例,我具有重复行的数据,这些重复行的日期值不同。我想合并重复的记录以减少行数,同时想计算记录的结束日期。 “ CountryCode”列应用于合并记录,“ CountryRiskLevel”或“ RegionRiskLevel”列中的值更改应用于定义开始和结束日期范围。 数据库-SQL Server。

谢谢, 哈利 enter image description here

1 个答案:

答案 0 :(得分:1)

尝试此查询,我使用了稍有不同的示例数据,但该查询同样适用于您:

;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