繁体   English   中英

MySQL我的总得分排名

[英]MySQL Rank my total score

我有一张表格,看起来像下面这样,没有等级字段。 我想将该排名字段放在下表中。 如何在MySQL中实现?

#   name    aa   bb   cc   total   |  rank
1    name1   20   20   30     70   |   1
2    name2   10   20   30     60   |   2
3    name3   20   10   25     55   |   3
4    name4   20   20   30     70   |   1
5    name5   10   10   20     40   |   4

这是一种方法,结果将相对于总数进行排序。

mysql> create table test (id int, name varchar(100),total int);
Query OK, 0 rows affected (0.13 sec)

mysql> insert into test values 
    -> (1,'name1',70),
    -> (2,'name2',60),
    -> (3,'name3',55),
    -> (4,'name4',70),
    -> (5,'name5',40);
Query OK, 5 rows affected (0.02 sec)


select 
id,
name, 
case 
when @cur_rank = total then @rank 
else @rank := @rank + 1 
end as rank, 
@cur_rank := total as total 
from test ,(select @rank:=0, @cur_rank:=0)r 
order by total desc ;


+------+-------+------+-------+
| id   | name  | rank | total |
+------+-------+------+-------+
|    1 | name1 |    1 |    70 |
|    4 | name4 |    1 |    70 |
|    2 | name2 |    2 |    60 |
|    3 | name3 |    3 |    55 |
|    5 | name5 |    4 |    40 |
+------+-------+------+-------+

尝试这个:-

SELECT #, name, aa, bb, cc, total, FIND_IN_SET( total, (
                                                SELECT GROUP_CONCAT( total ORDER BY total DESC ) 
                                                FROM your_tab
                                                        )
                                               ) AS rank
FROM your_tab;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM