2015-11-05 70 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(但外部应用示例按预期工作) –