简体   繁体   English

SQL获取列中的下一个非空值

[英]SQL to get next not null value in column

How can I get next not null value in column?如何获得列中的下一个非空值? I have MSSQL 2012 and table with only one column.我有 MSSQL 2012 和只有一列的表。 Like this:像这样:

rownum    Orig
------    ----
1         NULL
2         NULL
3         9
4         NULL
5         7
6         4
7         NULL
8         9

and I need this data:我需要这些数据:

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

Code to start:启动代码:

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;

One method is to use outer apply :一种方法是使用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;

One way you can do this with window functions (in SQL Server 2012+) is to use a cumulative max on id, in inverse order:您可以使用窗口函数(在 SQL Server 2012+ 中)执行此操作的一种方法是在 id 上以相反的顺序使用累积最大值:

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;

The subquery gets the value of the next non- NULL id.子查询获取下一个非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 ).然后,外部查询将orig值分布在所有具有相同 id 的行上(请记住,在具有相同nextid一组行中,只有一个的orig具有非NULL值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM