Sql 合并覆盖
我有一个包含人员及其覆盖期的sql表。很多人都有多个条目,只有在覆盖范围连续的情况下,才应该压缩这些条目。值是varchars,但我可以更改为其他值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
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;