[英]Get the second highest max for each value on Oracle
I want to get the second highest max using PL/SQL (Oracle).我想使用 PL/SQL (Oracle) 获得第二高的最大值。
I have a table that looks like this:我有一张看起来像这样的表:
CLIENT | ORDER_DATE
1 | 14/09/2018
1 | 01/02/2019
2 | 13/12/2019
2 | 01/01/2020
2 | 15/12/2019
I want to get a table with the max(ORDER_DATE) and the 2nd highest max(ORDER_DATE) for each client:我想为每个客户端获取一个包含 max(ORDER_DATE) 和第二高 max(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
I have tried using rank, but got only one row (one random client):我尝试使用排名,但只有一行(一个随机客户端):
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
You need conditional aggregation after appyling analytic function such as ROW_NUMBER()
:在应用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
You can try the below - use partition by client
in over()
clause您可以尝试以下操作 - 在over()
子句中partition by client
使用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
You can do this using analytic functions as well:您也可以使用分析函数执行此操作:
select distinct client,
max(date) over (partition by client),
nth_value(date, 2) over (partition by client order by date desc)
from order_date;
Happily, Oracle supports nth_value()
as an analytic function.令人高兴的是,Oracle 支持nth_value()
作为分析函数。 Sadly, Oracle does not offer the same functionality as a simpler aggregation function.遗憾的是,Oracle 没有提供与更简单的聚合函数相同的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.