如何在oracle中为具有先前第一个非空值的空值分配等级

how to assign a rank for null values with previous first non-null value in oracle

我需要为有序行的一些空值分配排名。
我的查询是这样的:

with sub as 
(
 select 10 as id, 1 as inx,2 as num from dual
  union all
 select 10 as id, 2 as inx,null as num from dual
  union all
 select 10 as id, 3 as inx,8 as num from dual
  union all
 select 10 as id, 4 as inx,null as num from dual
)
select *
  from sub order by inx

结果集是这样的:

id  inx  num
---------- 
10  1    2
10  2    null
10  3    8
10  4    null

我尝试用之前的第一个非空值设置空值
例如:num null 值应为“2”,其中 inx = 2
num null 值应为“8”,其中 inx = 4 等等。

感谢任何想法..

如果你知道值在增加,你可以使用 max():

select id, inx, max(num) over (partition by id order by inx) as num

如果它们没有增加并且多个空值从未出现在序列中,您可以使用 lag():

select id, inx,
       (case when num is null
             then lag(num) over (partition by id order by inx)
             else num
        end)as null;

如果序列中确实出现空值,您可以使用 ignore nulls 选项 lag():

select id, inx,
       (case when num is null
             then lag(num ignore nulls) over (partition by id order by inx)
             else num
        end)as null