Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 合并覆盖_Sql_Sql Server_Sql Update - Fatal编程技术网

Sql 合并覆盖

Sql 合并覆盖,sql,sql-server,sql-update,Sql,Sql Server,Sql Update,我有一个包含人员及其覆盖期的sql表。很多人都有多个条目,只有在覆盖范围连续的情况下,才应该压缩这些条目。值是varchars,但我可以更改为其他值 Name effective termination John 20160101 20160315 John 20160316 20160501 John 20160601 20161101 John 20160701 20160731 John 20160801 2016123

我有一个包含人员及其覆盖期的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

这是我的想法。确定每组覆盖范围的起始位置。使用此信息来识别组。然后聚合得到您想要的:

  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;