繁体   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