子查询中每个组的最大值
Max value for each group in subquery
我有一个包含 10 列的 table,我对其中的 3 列感兴趣。
说 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
所以,我想要的是 ID 为 5 和 6 的行的所有列。这将是每个组(苹果、橙色)排名最高的行
使用 row_number
按降序对每个名称组中的行进行编号,select 每个组的第一行。
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
我有一个包含 10 列的 table,我对其中的 3 列感兴趣。 说 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
所以,我想要的是 ID 为 5 和 6 的行的所有列。这将是每个组(苹果、橙色)排名最高的行
使用 row_number
按降序对每个名称组中的行进行编号,select 每个组的第一行。
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