SQL获取列中的下一个非空值 [英] SQL to get next not null value in column
本文介绍了SQL获取列中的下一个非空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取列中的下一个非空值?我有 MSSQL 2012 和只有一列的表.像这样:
How can I get next not null value in column? I have MSSQL 2012 and table with only one column. Like this:
rownum Orig
------ ----
1 NULL
2 NULL
3 9
4 NULL
5 7
6 4
7 NULL
8 9
我需要这些数据:
Rownum Orig New
------ ---- ----
1 NULL 9
2 NULL 9
3 9 9
4 NULL 7
5 7 7
6 4 4
7 NULL 5
8 9 5
启动代码:
declare @t table (rownum int, orig int);
insert into @t values (1,NULL),(2,NULL),(3,9),(4,NULL),(5,7),(6,4),(7,NULL),(8,9);
select rownum, orig from @t;
推荐答案
一种方法是使用outer apply
:
select t.*, t2.orig as newval
from @t t outer apply
(select top 1 t2.*
from @t t2
where t2.id >= t.id and t2.orig is not null
order by t2.id
) t2;
您可以使用窗口函数(在 SQL Server 2012+ 中)执行此操作的一种方法是在 id 上以相反的顺序使用累积最大值:
One way you can do this with window functions (in SQL Server 2012+) is to use a cumulative max on id, in inverse order:
select t.*, max(orig) over (partition by nextid) as newval
from (select t.*,
min(case when orig is not null then id end) over (order by id desc) as nextid
from @t
) t;
子查询获取下一个非NULL
id 的值.然后外部查询将 orig
值传播到所有具有相同 id 的行(请记住,在具有相同 nextid
的一组行中,只有一个将具有非NULL
值用于 orig
).
The subquery gets the value of the next non-NULL
id. The outer query then spreads the orig
value over all the rows with the same id (remember, in a group of rows with the same nextid
, only one will have a non-NULL
value for orig
).
这篇关于SQL获取列中的下一个非空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文