从连续两个月中查找第二个最大日期 - PL SQL

Find Second maximum date from two consecutive months - PL SQL

我有一个数据 table 包含连续两个月的日期,我需要使用 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

在分析函数的帮助下(第 1 - 6 行中的示例数据;temp CTE“计算”每个 status_date 的排名;最终查询(第 12 行开始)returns 结果):

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>

从 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<>fiddle here