简体   繁体   English

如何获得Oracle中每个组的最大值?

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

I've found some solutions for this problem, however, they don't seem to work with Oracle.我为这个问题找到了一些解决方案,但是,它们似乎不适用于 Oracle。

I got this:我懂了:

在此处输入图片说明

I want a view to present only the informations about the oldest person for each team.我想要一个视图,只显示每个团队最年长的人的信息。 So, my output should be something like this:所以,我的输出应该是这样的:

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

How can I do that in Oracle?我怎样才能在 Oracle 中做到这一点?

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

One method uses keep :一种方法使用keep

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

There are other methods, but in my experience, keep works quite well.还有其他方法,但根据我的经验, keep效果很好。

Here is an example without keep but with row_number() :这是一个没有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;

Using an Analytic Function returns all people with maximum age per team (needed if there are people with identical ages), selects Table one time only and is thus faster than other solutions that reference Table multiple times:使用分析函数返回每个团队的所有最大年龄的人(如果有相同年龄的人需要),只选择一次表,因此比多次引用表的其他解决方案更快:

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

This also works in MySQL/MariaDB.这也适用于 MySQL/MariaDB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM