我有一张表格(称为用户),我需要根据用户的得分对其进行排名,但我希望根据用户的最高得分进行排名。
+-----------+------------+ | User_id | Score | +-----------+------------+ | 1 | 12258 | | 1 | 112 | | 2 | 9678 | | 5 | 9678 | | 3 | 689206 | | 3 | 1868 |
预期结果
+-----------+------------+---------+ | User_id | Score | Rank | +-----------+------------+---------+ | 3 | 689206 | 1 | | 1 | 12258 | 2 | | 2 | 9678 | 3 | | 5 | 9678 | 3 |
您正在寻找DENSE_RANK,但它支持高于8.0的mysql版本
DENSE_RANK
max
User_id
rank
看起来像这样。
CREATE TABLE T( User_id int, Score int ); insert into t values (1,12258); insert into t values (1,112); insert into t values (2,9678); insert into t values (5,9678); insert into t values (3,689206); insert into t values (3,1868);
查询1 :
SELECT User_id,Score,Rank FROM ( SELECT User_id, Score, @rank :=IF(@previous = t1.score, @rank, @rank + 1) Rank, @previous := t1.Score FROM T t1 CROSS JOIN (SELECT @Rank := 0,@previous := 0) r WHERE t1.Score = ( SELECT MAX(Score) FROM T tt WHERE t1.User_id = tt.User_id ) ORDER BY Score desc ) t1
结果 :
| User_id | Score | Rank | |---------|--------|------| | 3 | 689206 | 1 | | 1 | 12258 | 2 | | 2 | 9678 | 3 | | 5 | 9678 | 3 |