Amy123
Amy123

Reputation: 972

Max value for each group in subquery

I have a table with 10 columns and I am interested in 3 of those. Say tableA with id, name, url, ranking.

id    |name    |url    |ranking
--------------------------------
1     |apple   |a1.com |1
2     |apple   |a1.com |2
3     |apple   |a1.com |3
4     |orange  |o1.com |1
5     |orange  |o1.com |2
6     |apple   |a1.com |4

So, what I want is, all the columns for row with id 5 and 6. That would be row with maximum ranking for each group (apple, orange)

Upvotes: 0

Views: 936

Answers (1)

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49260

Use row_number to number the rows in each name group by their ranking in the descending order and select the the first row per each group.

select id,name,url,ranking
from
(select t.*, row_number() over(partition by name order by ranking desc) as rn
from tablename t) t 
where rn =1

Upvotes: 1

Related Questions