我们有一个表格,其中包含有效日期,CVal,CPrice列
我们如何查询表以返回1行中这两行的值:
具有有效日期的行中的CVal(NextVal)和CPrice(NextPrice)值是某个日期之后的下一个日期
CVal(SecondVal)和CPrice(SecondPrice)值位于#1的有效日期之后的下一个日期
例如:
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'
预期结果
(“有效日期”列中“ 31-DEC-19”之后的下一个日期是20年1月1日,
,其后的下一个日期是21年1月1日):
NextVal NextPrice SecondVal SecondPrice
2 101 3 102
谢谢。
使用zip中的答案进行编辑(将topnum替换为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
答案 0 :(得分:1)
您可以使用窗口功能
select
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'
where rownum = 1
order by Effective_Date
输出为
NextVal NextPrice SecondVal SecondPrice
2 101 3 102
答案 1 :(得分:0)
如果只需要一行,则可以对表进行过滤和排序并限制值:
select t.*
from (select t.*
from t
where t.effective_date > date '2019-12-31'
order by t.effective_date
) t
where rownum = 1;
然后,您可以添加lead()
,以从“下一个”行中拉出其他列:
select t.*
from (select t.*, lead(cval) over (order by effective_date) as next_cval,
lead(price) over (order by effective_date) as next_price
from t
where t.effective_date > date '2019-12-31'
order by t.effective_date
) t
where rownum = 1;