MySQL query to display ranks of multiple columns?


For this, use FIND_IN_SET() method. Let us first create a table −

mysql> create table DemoTable634 (FirstName varchar(100),Marks int,Age int);
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable634 values('John',60,23);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable634 values('Chris',80,21);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable634 values('Robert',70,24);
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable634;

This will produce the following output −

+-----------+-------+------+
| FirstName | Marks | Age  |
+-----------+-------+------+
| John      |    60 |   23 |
| Chris     |    80 |   21 |
| Robert    |    70 |   24 |
+-----------+-------+------+
3 rows in set (0.00 sec)

Following is the query to display ranks of multiple columns −

mysql> SELECT FirstName,Marks,Age,
   FIND_IN_SET( Marks,( SELECT GROUP_CONCAT( Marks ORDER BY Marks DESC ) FROM DemoTable634)) AS RankOfMarks,
   FIND_IN_SET(Age,( SELECT GROUP_CONCAT( Age ORDER BY Age DESC ) FROM DemoTable634) ) AS RankOfAge
   FROM DemoTable634;

This will produce the following output displaying the rank on the basis of marks and age −

+-----------+-------+------+-------------+-----------+
| FirstName | Marks | Age  | RankOfMarks | RankOfAge |
+-----------+-------+------+-------------+-----------+
| John      |    60 |   23 |           3 |         2 |
| Chris     |    80 |   21 |           1 |         3 |
| Robert    |    70 |   24 |           2 |         1 |
+-----------+-------+------+-------------+-----------+
3 rows in set (0.01 sec)

Updated on: 23-Aug-2019

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements