【问题标题】:Find Second maximum date from two consecutive months - PL SQL [duplicate]从连续两个月中查找第二个最大日期-PL SQL [重复]
【发布时间】:2021-11-24 09:25:18
【问题描述】:

我有一个包含日期的数据表,我需要使用 PL/SQL 从中找到第二个最大日期

Date
02-OCT-2021
30-SEP-2021
29-SEP-2021
28-SEP-2021

我的查询是,

select MAX(status_date) from A where status_date not in (select MAX(status_date) from A)

29-SEP-2021 是查询结果,但应该是30-SEP-2021

【问题讨论】:

    标签: sql oracle date


    【解决方案1】:

    借助分析函数(第 1 - 6 行中的样本数据;temp CTE “计算”每个 status_date 的排名;最终查询(第 12 行向前)返回结果):

    SQL> alter session set nls_date_format = 'dd.mm.yyyy';
    
    Session altered.
    
    SQL> with a (status_date) as
      2    (select date '2021-10-02' from dual union all
      3     select date '2021-09-30' from dual union all
      4     select date '2021-09-29' from dual union all
      5     select date '2021-09-28' from dual
      6    ),
      7  temp as
      8    (select status_date,
      9            rank() over (order by status_date desc) rnk
     10     from a
     11    )
     12  select status_date
     13  from temp
     14  where rnk = 2;
    
    STATUS_DAT
    ----------
    30.09.2021
    
    SQL>
    

    【讨论】:

    • RANK 是错误的函数。如果有与最新日期相同的值,则不会有排名为 2 的行。db<>fiddle
    【解决方案2】:

    从 Oracle 12 开始,您可以使用:

    SELECT *
    FROM   table_name
    ORDER BY date_column DESC
    OFFSET 1 ROW FETCH NEXT 1 ROW ONLY;
    

    在此之前,您可以使用:

    SELECT date_column
    FROM   (
      SELECT date_column,
             ROW_NUMBER() OVER (ORDER BY date_column DESC) AS rn
      FROM   table_name
      ORDER BY date_column DESC
    )
    WHERE rn = 2;
    

    或:

    SELECT date_column
    FROM   (
      SELECT date_column,
             ROWNUM AS rn
      FROM   (
        SELECT date_column
        FROM   table_name
        ORDER BY date_column DESC
      )
    )
    WHERE rn = 2;
    

    db小提琴here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多