Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何获取表中下一个日期和下一个日期的值_Sql_Oracle_Date_Oracle11g - Fatal编程技术网

Sql 如何获取表中下一个日期和下一个日期的值

Sql 如何获取表中下一个日期和下一个日期的值,sql,oracle,date,oracle11g,Sql,Oracle,Date,Oracle11g,我们有一个表,列有生效日期、CVal、CPrice 我们如何查询该表以从一行中的这两行返回值: CVal NextVal和CPrice NextPrice值来自生效日期为somedate后的下一个日期的行 CVal SecondVal和CPrice SecondPrice值来自生效日期在生效日期1之后的下一个日期的行 例如: Effective_Date CVal CPrice 01-JAN-19 1 100 01-JAN-20 2 101

我们有一个表,列有生效日期、CVal、CPrice

我们如何查询该表以从一行中的这两行返回值:

CVal NextVal和CPrice NextPrice值来自生效日期为somedate后的下一个日期的行

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='19年12月31日'

预期结果

生效日期栏中“19年12月31日”之后的下一个日期是20年1月1日

之后的下一个日期是21年1月1日:

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

您可以使用窗口功能来实现它

    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

如果只需要一行,可以对表进行筛选和排序,并限制值:

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;

我用zip的答案编辑了我的原始帖子。谢谢你的支持help@faujong . . . 令人惊讶的是,您接受了这个答案,因为该代码在Oracle中不起作用。