我已经找到了解决此问题的方法,但是,它们似乎与Oracle无关。
我明白了:
我想要一个视图,只显示每个团队中最老的人的信息。所以,我的输出应该是这样的:
PERSON | TEAM | AGE
Sam | 1 | 23
Michael | 2 | 21
我怎样才能在Oracle中做到这一点?
答案 0 :(得分:2)
一种方法使用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
效果很好。
答案 1 :(得分:2)
以下是没有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;
答案 2 :(得分:1)
select * from table
where (team, age) in (select team, max(age) from table group by team)
答案 3 :(得分:0)
select * from (select person,team,age,
dense_rank() over (partition by team order by age desc) rnk)
where rnk=1;
答案 4 :(得分:0)
使用分析函数返回每个团队中所有年龄最大的人(如果有相同年龄的人需要),只选择一次表,因此比多次引用表的其他解决方案更快:
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。