我有一个看起来像下面没有排名字段的表。我想把这个等级字段放在下表中。我怎样才能在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
答案 0 :(得分:1)
这是一种方法,结果将根据总数进行排序。
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 |
+------+-------+------+-------+
答案 1 :(得分:-1)
试试这个: -
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;