如何选择列值最高的行,如果重复则返回最上面的行?

时间:2019-01-30 12:10:47

标签: mysql sql

我有一个名为class RegistrationHandler(tornado.web.RequestHandler): def post(self, *args, **kwargs): call_async_register("some params") def call_async_register(parameters): def call(): http_client = AsyncHTTPClient() future = Future() http_request = HTTPRequest(url, request_type.name, headers={'X-Peering': '1'}, body=body) def handle_future(f: Future): future.set_result(f.result()) fetched_future = http_client.fetch(http_request) fetched_future.add_done_callback(handle_future) return future try: instance = io_loop.IOLoop.current() response = instance.run_sync(call) return response.body.decode() except Exception as err: self.logger.exception("Account Request Failed: {}".format(err)) return None 的表,该表包含两列:player_ratingsplayer_id。例如:

rating

我想返回玩家评分最高的玩家列表。

如果表中有重复的行,则返回最上面的行。例如, | player_id | rating | | 1 | 950 | | 1 | 945 | | 2 | 850 | | 2 | 850 | 2具有两行,且同一行player_id,因此返回表中的第3行。

该列表中不应包含任何重复的玩家。 (请参阅预期的输出)

我尝试了以下查询,但没有删除重复的行:

rating

实际输出

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 ;

预期输出

 |  player_id     |       ranking       | 
 |     1          |         950         |
 |     2          |         850         |
 |     2          |         850         |

4 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

   SELECT player_id, MAX(rating) as max_rating FROM player_ratings 
   GROUP BY player_id
   order by max_rating desc

答案 1 :(得分:0)

由于只有两列,即玩家ID和排名,您可以简单地进行汇总:

select player_id, max(rating)
from player_ratings
group by player_id
order by max(rating) desc;

答案 2 :(得分:0)

假设您在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
                              );

答案 3 :(得分:0)

使用GROUP BYMAX()

SELECT player_id, MAX(rating) as Rating
FROM player_ratings GROUP BY player_id
ORDER BY 2 DESC