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

11
我已经找到了一些解决方案,但它们似乎不能与Oracle一起使用。
我得到了这个:

enter image description here

我希望有一个视图,只展示每个团队中年龄最大的人的信息。因此,我的输出应该类似于这样:

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

我该如何在Oracle中实现这个?

5个回答

10
以下是与 row_number() 相关的示例,但没有keep 的实现:

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;

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

2
从我的测试来看,这种方法比其他在这里提出的方法要慢得多。 - AverageJon

5

其中一种方法是使用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”。 - user7243231
我认为这是所有答案中最简单的方法。然而,FIRST并不是那么常见的知识。 - Wernfried Domscheit
很好,但是当我添加更多行时它会扩展。如何保留其他列以供我查询这些行? - Peter.k
@Peter.k . . . 我建议你提出一个新的问题,附上适当的示例数据、期望的结果以及对你想要做什么的解释。 - Gordon Linoff

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。


1

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

1
子查询中没有from子句,看起来是无效的。这不是你要找的select语句。 - Software Prophets

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接