【问题标题】:Grouping duplicate rows and calculating effective and end dates对重复行进行分组并计算生效日期和结束日期
【发布时间】:2019-01-16 10:26:50
【问题描述】:

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

谢谢, 哈利

【问题讨论】:

  • 请提供您的 dbmas 名称
  • @Zaynul Abadin Tuhin - SQL Server

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


【解决方案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

【讨论】:

  • 感谢您的回复。完美运行。我必须稍微修改脚本以使其适用于大量数据。再次感谢,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 2020-08-21
  • 2019-12-18
  • 2023-02-23
  • 1970-01-01
  • 2013-05-25
相关资源
最近更新 更多