簡體   English   中英

如何獲得Oracle中每個組的最大值?

[英]How to get the max value for each group in Oracle?

我為這個問題找到了一些解決方案,但是,它們似乎不適用於 Oracle。

我懂了:

在此處輸入圖片說明

我想要一個視圖,只顯示每個團隊最年長的人的信息。 所以,我的輸出應該是這樣的:

PERSON  | TEAM | AGE
Sam     | 1    | 23
Michael | 2    | 21

我怎樣才能在 Oracle 中做到這一點?

select * from table
where (team, age) in (select team, max(age) from table group by team)

一種方法使用keep

select team, max(age) as age,
       max(person) keep (dense_rank first order by age desc) as person
from t
group by team;

還有其他方法,但根據我的經驗, keep效果很好。

這是一個沒有keep但有row_number()的例子:

with t0 as
(
  select person, team, age,
  row_number() over(partition by team order by age desc) as rn
  from t
)
select person, team, age
from t0
where rn = 1;

select * from (select person,team,age,
       dense_rank() over (partition by team order by age desc) rnk)
       where rnk=1;

使用分析函數返回每個團隊的所有最大年齡的人(如果有相同年齡的人需要),只選擇一次表,因此比多次引用表的其他解決方案更快:

With MaxAge as (
  Select T.*, Max (Age) Over (Partition by Team) MaxAge
  From Table T
)
Select Person, Team, Age From MaxAge Where Age=MaxAge
;

這也適用於 MySQL/MariaDB。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM