简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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