问题
We have a table with columns Effective_Date, CVal,CPrice
How do we query the table to return values from these 2 rows in 1 row:
CVal (NextVal) and CPrice (NextPrice) values from row with Effective_Date the next date after somedate
CVal (SecondVal) and CPrice (SecondPrice) values from row with Effective_Date the next date after the Effective_Date from #1
For ex:
Effective_Date CVal CPrice
01-JAN-19 1 100
01-JAN-20 2 101
01-JAN-21 3 102
01-JAN-22 4 103
Say somedate = '31-DEC-19'
Expected result
(the next date after '31-DEC-19' in the Effective_Date column is 01-JAN-20,
and the next date after that is 01-JAN-21):
NextVal NextPrice SecondVal SecondPrice
2 101 3 102
Thank you.
Edited with answer from zip (replaced "top" with where rownum = 1, since top doesn't work on my 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
回答1:
You can use the window functions for it
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
Output is
NextVal NextPrice SecondVal SecondPrice
2 101 3 102
回答2:
If you want just one row, you can filter and order the table and limit the values:
select t.*
from (select t.*
from t
where t.effective_date > date '2019-12-31'
order by t.effective_date
) t
where rownum = 1;
Then you can add lead()
to pull in additional columns from the "next" row:
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;
来源:https://stackoverflow.com/questions/59901871/how-to-get-the-values-for-the-next-and-next-next-date-in-a-table