Как получить значения для следующей и следующей следующей даты в таблице - PullRequest
0 голосов
/ 24 января 2020

У нас есть таблица со столбцами Effective_Date, CVal, CPrice

Как запросить таблицу, чтобы получить значения из этих 2 строк в 1 строке:

  1. CVal Значения (NextVal) и CPrice (NextPrice) из строки с Effective_Date на следующую дату после некоторой даты

  2. Значения CVal (SecondVal) и CPrice (SecondPrice) из строки с Effective_Date на следующую дату после Effective_Date от # 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

Say somedate = '31 -DE C -19 '

Ожидаемый результат

(следующая дата после '31 -DE C -19 'в столбце Effective_Date - 01-JAN-20,

, а следующая дата после этого - 01-JAN-21):

NextVal NextPrice SecondVal SecondPrice
2       101       3         102

Спасибо.

Отредактировано с ответом от zip (заменил "top" на где 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

Ответы [ 2 ]

2 голосов
/ 24 января 2020

Вы можете использовать для этого функции окна

    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 голос
/ 24 января 2020

Если вам нужна только одна строка, вы можете отфильтровать и упорядочить таблицу и ограничить значения:

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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...