[英]How to select rows with the highest column value and in case of duplicates return the top most row?
I have a table called player_ratings
which contains two columns: player_id
and rating
. 我有一个名为
player_ratings
的表,该表包含两列: player_id
和rating
。 For example: 例如:
| player_id | rating |
| 1 | 950 |
| 1 | 945 |
| 2 | 850 |
| 2 | 850 |
I want to return a list of players with the highest player_rating. 我想返回玩家等级最高的玩家列表。
If there are duplicate rows in the table, return the topmost row. 如果表中有重复的行,则返回最上面的行。 For example,
player_id
2 has two rows with the same rating
so return row 3 in the table. 例如,
player_id
2有两行具有相同的rating
因此请返回表中的第3行。
the list shouldn't contain any duplicate players. 列表中不应包含任何重复的玩家。 (see the expected output)
(请参阅预期的输出)
I tried the following query but it doesn't remove duplicates rows: 我尝试了以下查询,但它不会删除重复的行:
SELECT *
FROM player_ratings
INNER JOIN ( SELECT player_id, MAX(rating) as max_rating FROM player_ratings GROUP BY player_id) topratings
ON player_ratings.player_id = topratings.player_id
AND player_ratings.rating = topratings.max_rating
ORDER BY player_ratings.rating DESC ;
ACTUAL OUTPUT 实际输出
| player_id | ranking |
| 1 | 950 |
| 2 | 850 |
| 2 | 850 |
EXPECTED OUTPUT 预期的输出
| player_id | ranking |
| 1 | 950 |
| 2 | 850 |
You can try below - 您可以在下面尝试-
SELECT player_id, MAX(rating) as max_rating FROM player_ratings
GROUP BY player_id
order by max_rating desc
As it's just about two columns, the player ID and the ranking, you can simply aggregate: 由于只有两列,即玩家ID和排名,您可以简单地进行汇总:
select player_id, max(rating)
from player_ratings
group by player_id
order by max(rating) desc;
Assuming you have a unique id in player_ratings
, then you can do: 假设您在
player_ratings
具有唯一的ID,则可以执行以下操作:
select pr.*
from player_ratings pr
where pr.player_ratings_id in (select pr2.player_ratings_id
from player_ratings pr2
where pr2.player_id = pr.player_id
order by pr2.max_rating desc,
pr2.player_ratings_id asc
);
Use GROUP BY
and MAX()
使用
GROUP BY
和MAX()
SELECT player_id, MAX(rating) as Rating
FROM player_ratings GROUP BY player_id
ORDER BY 2 DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.