2

I have a table that looks something like below without the rank field. I want to put that rank field as it is in the table below. How can I achieve it in 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
Luke Peterson
  • 8,584
  • 8
  • 45
  • 46
Ikong
  • 2,540
  • 4
  • 38
  • 58

2 Answers2

1

Here is a way to do it, the result will be sorted with respect to the total.

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 |
+------+-------+------+-------+
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
-1

Try this:-

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;
Ankit Bajpai
  • 13,128
  • 4
  • 25
  • 40