【问题标题】:How to get the values for the next and next next date in a table如何获取表中下一个和下一个下一个日期的值
【发布时间】:2020-05-11 02:25:50
【问题描述】:

我们有一个包含 Effective_Date、CVal、CPrice 列的表

我们如何查询表以在 1 行中从这 2 行返回值:

  1. 在某个日期之后的下一个日期为 Effective_Date 的行中的 CVal (NextVal) 和 CPrice (NextPrice) 值

  2. 来自 #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

【问题讨论】:

    标签: sql oracle date oracle11g


    【解决方案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
    

    【讨论】:

    • @faujong 。 . .鉴于代码在 Oracle 中不起作用,您接受了这个答案令人惊讶。
    【解决方案2】:

    如果你只想要一行,你可以过滤和排序表格并限制值:

    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 的答案编辑了我的原始帖子。感谢您的帮助
    猜你喜欢
    • 2020-05-11
    • 2012-12-11
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多