MySQL Rank in the Case of Ties

旧街凉风 提交于 2019-12-01 13:23:28

问题


I need some help dealing with ties when ranking in MySQL. For example:

PLAYER | POINTS

  • Mary: 90
  • Bob: 90
  • Jim: 65
  • Kevin: 12

Bob and Mary should both be ranked #1. Jim should be #3. Kevin should be #4.

MySQL:

SET @rank=0;
SELECT @rank:=@rank +1 as rank, player, points FROM my_table

How can I change the SELECT statement so that the ranking is correct in the case of ties?

My real life problem is more complicated, but if I understand how to solve the above, then I should be set.


回答1:


Assuming name is unique

SELECT t1.name, (SELECT COUNT(*) FROM table_1 t2 WHERE t2.score > t1.score) +1
AS rnk
FROM table_1 t1



回答2:


SELECT players.*, COUNT(higher_ranking.id) + 1 AS rank
    FROM players
    LEFT JOIN players AS higher_ranking
        ON higher_ranking.points > players.points
    GROUP BY players.id

On Postgres, you could use window functions RANK() to achieve this, which is much nicer. I don't know of anything like that for MySQL.



来源:https://stackoverflow.com/questions/7100010/mysql-rank-in-the-case-of-ties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!