SQL Server更新不包含按连续数字和null排序的null的行

时间:2018-08-15 02:06:17

标签: sql-server null grouping gaps-and-islands

我有查询返回了几行。有连续数字的列,其中为空。

例如,其值的范围是1-10,然后是5个空值,然后是16-30,然后是10空值,然后是41-45,依此类推。

我需要更新该列或创建另一个列以为连续列创建groupId。

按照上面的示例的意思,对于行1-10,groupID可以为1。然后对于5,null则什么都不是,然后对于16-30,groupId可以为2。然后对于10 null则什么都不是。然后从41-45的groupId可以是3,依此类推。

请让我知道

2 个答案:

答案 0 :(得分:2)

这很有趣。这是一个简单的表的解决方案,该表仅包含整数,但带有空格。

create table n(v int)
insert n values (1),(2),(3),(5),(6),(7),(9),(10)

select n.*, g.group_no
from n
join (
select row_number() over (order by low.v) group_no, low.v as low, min(high.v) as high
from n as low
join n as high on high.v>low.v 
    and not exists(select * from n h2 where h2.v=high.v+1)
where not exists(select * from n l2 where l2.v=low.v-1)
group by low.v
) g on g.low<=n.v and g.high>=n.v

结果:

v   group_no
1   1
2   1
3   1
5   2
6   2
7   2
9   3
10  3

答案 1 :(得分:1)

典型的岛隙解决方案

select  col, grp = dense_rank() over (order by grp)
from    
(
    select  col, grp = col - dense_rank() over (order by col)
    from    yourtable
) d