问题
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
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;
回答1:
One method is to use 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:
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. 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
).
来源:https://stackoverflow.com/questions/33553710/sql-to-get-next-not-null-value-in-column