获取列中下一个非空值的SQL
如何获取列中的下一个非空值?我有MSSQL 2012和只有一列的表。像这样:获取列中下一个非空值的SQL,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,如何获取列中的下一个非空值?我有MSSQL 2012和只有一列的表。像这样: rownum Orig ------ ---- 1 NULL 2 NULL 3 9 4 NULL 5 7 6 4 7 NULL 8 9 我需要这些数据: Rownum Orig New ------ ---- ---- 1 NULL
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;
一种方法是使用
外部应用
:
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:
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
).一种方法是使用外部应用
:
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:
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
).您使用的是什么版本的SQL Server?您使用的是什么版本的SQL Server?太好了!但是您的第二个示例可能包含拼写错误-它不起作用expected@AlexanderSigachov你说“可能有打字错误”是什么意思???张贴的代码在我看来非常好。还有,“不按预期工作”是什么意思?在我的数据上,它总是得到“9”作为newval(但外部应用示例按预期工作)@AlexanderSigachov。第二种方法应该使用min()
而不是max()
。按排序的是降序而不是升序。太好了!但是您的第二个示例可能包含拼写错误-它不起作用expected@AlexanderSigachov你说“可能有打字错误”是什么意思???张贴的代码在我看来非常好。还有,“不按预期工作”是什么意思?在我的数据上,它总是得到“9”作为newval(但外部应用示例按预期工作)@AlexanderSigachov。第二种方法应该使用min()
而不是max()
。按
排序的是降序而不是升序。