sql - 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
先使用空值,但看不到让它工作。
解决方案
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_
推荐阅读
- excel - 安全删除未使用的编码:可以调用宏的所有方法是什么?
- r - 如何根据分号分隔列中的值过滤行?
- angular - Angular - 覆盖(仅)环境的一个属性
- spring-boot - Spring Boot Starter Data JPA - liquibase 错误
- cpu - VLIW 处理器如何处理可变时间操作?
- android - 使用 DisplayManager 或 MediaRouter 颤振多屏
- python - 将数组作为 .jpg 图像上传到 Azure Blob 存储
- linq - EF Core 3.1 在运行时生成的表达式都失败,无法处理服务器上的查询
- samesite - SameSite="Lax" 和 SameSite="Strict" 有什么区别?
- reactjs - 如何使用 thunk 在 react-redux 挂钩中进行异步调用?