LAG 和第一个 NULL

LAG and the first NULL

我有以下 table:

id    date       cust
1     3/13/2019  
1     3/14/2019  Johnson
1     3/19/2019 

我想创建一个列来捕获最后一个客户条目并按 ID 进行分区。

我有以下..

select *
,case
 when a.cust is not null then a.cust
 else lag(a.cust) over partition by a.id order by a.date)
 end lst_cust
from A

结果:

id  date        cust
 1   3/13/2019
 1   3/14/2019  Johnson
 1   3/19/2019  Johnson

如何为第一行捕获 "Johnson"?

我也在考虑使用 lead,但不确定如何将两者都嵌入到 case 表达式中,以及这是否正是我正在寻找的。或者 LAST_VALUE 首先使用空值,但看不到让它工作。

我想你想要 lead()lag():

select a.*,
       coalesce(a.cust, 
                lag(a.cust) over partition by a.id order by a.date),
                lead(a.cust) over partition by a.id order by a.date)
               ) as lst_cust
from A;

如果可以连续放置多个 null,您可能还需要一个 ignore nulls

last_value 是个好主意,只需添加 window 子句:

select id, date_, 
       nvl(cust, last_value(cust) ignore nulls over (partition by id order by date_ 
                 rows between unbounded preceding and unbounded following)) cust
  from a
  order by id, date_

demo