首页 > 解决方案 > LAG 和第一个 NULL

问题描述

我有下表:

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

我想创建一个按 id 捕获最后一个 cust 条目和分区的列。

我有以下..

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

如何为第一行捕获“约翰逊”?

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

标签: sqloraclelaglead

解决方案


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

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_

演示


推荐阅读