【发布时间】:2020-05-11 02:25:50
【问题描述】:
我们有一个包含 Effective_Date、CVal、CPrice 列的表
我们如何查询表以在 1 行中从这 2 行返回值:
在某个日期之后的下一个日期为 Effective_Date 的行中的 CVal (NextVal) 和 CPrice (NextPrice) 值
来自 #1 的 Effective_Date 之后的下一个日期的 Effective_Date 行中的 CVal (SecondVal) 和 CPrice (SecondPrice) 值
例如:
Effective_Date CVal CPrice
01-JAN-19 1 100
01-JAN-20 2 101
01-JAN-21 3 102
01-JAN-22 4 103
说 somedate = '31-DEC-19'
预期结果
(Effective_Date 列中“31-DEC-19”之后的下一个日期是 01-JAN-20,
之后的下一个日期是 01-JAN-21):
NextVal NextPrice SecondVal SecondPrice
2 101 3 102
谢谢。
使用来自 zip 的答案进行编辑(将“top”替换为 where rownum = 1,因为 top 在我的 Oracle 上不起作用):
select t.* from
(
lead(CVal, 1) over(order by Effective_Date) as NextVal
,lead(CPrice, 1) over(order by Effective_Date) as NextPrice
,lead(CVal, 2) over(order by Effective_Date) as SecondVal
,lead(CPrice, 2) over(order by Effective_Date) as SecondPrice
from tbl where Effective_Date >= '31-DEC-19'
order by Effective_Date ) t
where rownum = 1
【问题讨论】: