Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I got this:

enter image description here

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?

like image 845
user7243231 Avatar asked Dec 02 '16 21:12

user7243231


4 Answers

select * from table
where (team, age) in (select team, max(age) from table group by team)
like image 104
arturro Avatar answered Sep 21 '22 08:09

arturro


Here is an example without keep but with 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;
like image 30
Nikita Kotlyarov Avatar answered Sep 18 '22 08:09

Nikita Kotlyarov


One method uses 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.

like image 41
Gordon Linoff Avatar answered Sep 18 '22 08:09

Gordon Linoff



select * from (select person,team,age,
       dense_rank() over (partition by team order by age desc) rnk)
       where rnk=1;
like image 33
Adwitiya Kumar Avatar answered Sep 20 '22 08:09

Adwitiya Kumar