【问题标题】:Get the second highest max for each value on Oracle获取 Oracle 上每个值的第二高最大值
【发布时间】:2020-12-31 18:48:04
【问题描述】:

我想使用 PL/SQL (Oracle) 获得第二高的最大值。

我有一张如下所示的表格:

CLIENT | ORDER_DATE
1      | 14/09/2018
1      | 01/02/2019
2      | 13/12/2019
2      | 01/01/2020
2      | 15/12/2019

我想为每个客户获取一个包含最大值(ORDER_DATE)和第二大最大值(ORDER_DATE)的表:

CLIENT | MAX(ORDER_DATE) | 2nd highest max(ORDER_DATE)
1      | 01/02/2019      | 14/09/2018
2      | 01/01/2020      | 15/12/2019

我尝试过使用排名,但只有一行(一个随机客户端):

select *
  from (select CLIENT,
               max(ORDER_DATE),
               row_number() over (order by max(ORDER_DATE) desc) as rk
          from order_table
         group by CLIENT) t
 where rk = 2

【问题讨论】:

    标签: sql oracle group-by window-functions


    【解决方案1】:

    您也可以使用分析函数来做到这一点:

    select distinct client, 
           max(date) over (partition by client),
           nth_value(date, 2) over (partition by client order by date desc)
    from order_date;
    

    令人高兴的是,Oracle 支持 nth_value() 作为分析函数。遗憾的是,Oracle 没有提供与更简单的聚合函数相同的功能。

    【讨论】:

      【解决方案2】:

      您可以尝试以下方法 - 在 over() 子句中使用 partition by client

      select client,max_date,order as seconf_highest_date from
      (
      select *,max(ORDER_DATE) over(partition by client order by ORDER_DATE desc) as max_date,
               row_number() over (partition by client order by ORDER_DATE desc) as rk
         from order_table
      )A where rk=2
      

      【讨论】:

        【解决方案3】:

        应用ROW_NUMBER()等解析函数后需要条件聚合:

        WITH t2 AS
        (
          SELECT client,order_date,
                 ROW_NUMBER() OVER (PARTITION BY client ORDER BY order_date DESC) as rk
           FROM order_table
        )
        SELECT client, 
               MAX(CASE WHEN rk=1 THEN order_date END) AS "max order date",
               MAX(CASE WHEN rk=2 THEN order_date END) AS "2nd highest max ord.date"
          FROM t2
         GROUP BY client
        

        Demo

        【讨论】:

          猜你喜欢
          • 2019-07-01
          • 2022-08-23
          • 1970-01-01
          • 2021-12-04
          • 2017-04-17
          • 2021-02-21
          • 1970-01-01
          • 2020-06-23
          相关资源
          最近更新 更多