2015-11-05 33 views
1

如何在列中獲得下一個非空值?我有MSSQL 2012和只有一列的表。就像這樣:SQL在列中獲得下一個非空值

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; 
+0

您使用的是哪個版本的SQL Server? –

回答

4

一種方法是使用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; 

的一種方式你可以用window functio來做到這一點NS(在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; 

子查詢獲取下一個非NULL id的值。外部查詢然後將orig值分佈在具有相同ID的所有行上(請記住,在具有相同nextid的一組行中,只有一個將具有orig的非NULL值)。

+0

太棒了!但你的第二個樣本可能包含錯別字 - 它不能按預期工作 –

+0

@AlexanderSigachov你是什麼意思「可能包含錯別字」???所發佈的代碼對我來說看起來非常好。另外,「不按預期工作」是什麼意思? –

+0

它總是在我的數據上得到「9」作爲newval(但外部應用示例按預期工作) –

相關問題