我有一张表格(称为用户),我需要根据用户的得分对其进行排名,但我希望根据用户的最高得分进行排名。
+-----------+------------+
| 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 |
答案 0 :(得分:2)
您正在寻找DENSE_RANK
,但它支持高于8.0的mysql版本
max
获取User_id
的值rank
,使用另一个变量来存储先前的值以制作DENSE_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
Results :
| User_id | Score | Rank |
|---------|--------|------|
| 3 | 689206 | 1 |
| 1 | 12258 | 2 |
| 2 | 9678 | 3 |
| 5 | 9678 | 3 |
答案 1 :(得分:2)