结合覆盖范围

时间:2017-01-26 18:44:33

标签: sql sql-server sql-update

我有一个包含人及其覆盖期的sql表。许多人有多个条目,这些条目只应在覆盖范围连续的情况下进行压缩。值是varchars但我可以更改为其他值。

Name    effective   termination
John    20160101    20160315
John    20160316    20160501
John    20160601    20161101
John    20160701    20160731
John    20160801    20161231

应该是

John    20160101    20160501
John    20160601    20161231

1 个答案:

答案 0 :(得分:1)

这是个主意。确定每组覆盖范围的开始位置。使用此信息来标识组。然后聚合得到你想要的东西:

  select name, min(effective) as effective, max(termination) as termination
  from (select t.*,
               sum(case when tprev.name is null then 1 else 0 end) over (partition by name order by effective) as grp
        from t left join
             t tprev
             on t.name = tprev.name and
                t.effective = dateadd(day, 1, tprev.termination)
       ) t
  group by name, grp;