这可以满足您的需求:
select t.id, t.val, DENSE_RANK() over (order by prevval) as grouping
from (select *,
(select top 1 id from @temp t2 where t2.val is not null and t2.id <= t.id order by id desc
) as prevval
from @temp t
) t
这使用一个相关的子查询来获取小于或等于给定值的最大id,其中
val
不为null(如果有)。然后,它根据id对这些进行密集排序,以获得顺序分组。
如果您使用的是SQL Server 2012,那么有一种相关的方法,没有子查询:
select t.id, t.val, DENSE_RANK() over (order by prevval) as grouping
from (select *,
max(case when val is not null then id end) over (order by id) as prevval
from @temp t
) t