Assigning Ranks
mysql>
mysql> CREATE TABLE testscore
-> (
-> subject INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> age INT UNSIGNED NOT NULL,
-> sex ENUM('M','F') NOT NULL,
-> score INT,
-> PRIMARY KEY (subject)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> INSERT INTO testscore (age,sex,score)
-> VALUES
-> (5,'M',5),
-> (5,'M',4),
-> (5,'F',6),
-> (5,'F',7),
-> (6,'M',8),
-> (6,'M',9),
-> (6,'F',4),
-> (6,'F',6),
-> (7,'M',8),
-> (7,'M',6),
-> (7,'F',9),
-> (7,'F',7),
-> (8,'M',9),
-> (8,'M',6),
-> (8,'F',7),
-> (8,'F',10),
-> (9,'M',9),
-> (9,'M',7),
-> (9,'F',10),
-> (9,'F',9)
-> ;
Query OK, 20 rows affected (0.00 sec)
Records: 20 Duplicates: 0 Warnings: 0
mysql>
mysql>
mysql> SELECT score FROM testscore ORDER BY score DESC;
+-------+
| score |
+-------+
| 10 |
| 10 |
| 9 |
| 9 |
| 9 |
| 9 |
| 9 |
| 8 |
| 8 |
| 7 |
| 7 |
| 7 |
| 7 |
| 6 |
| 6 |
| 6 |
| 6 |
| 5 |
| 4 |
| 4 |
+-------+
20 rows in set (0.00 sec)
mysql>
mysql> SET @rownum := 0;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> SELECT @rownum := @rownum + 1 AS rank, score FROM testscore ORDER BY score DESC;
+------+-------+
| rank | score |
+------+-------+
| 1 | 10 |
| 2 | 10 |
| 3 | 9 |
| 4 | 9 |
| 5 | 9 |
| 6 | 9 |
| 7 | 9 |
| 8 | 8 |
| 9 | 8 |
| 10 | 7 |
| 11 | 7 |
| 12 | 7 |
| 13 | 7 |
| 14 | 6 |
| 15 | 6 |
| 16 | 6 |
| 17 | 6 |
| 18 | 5 |
| 19 | 4 |
| 20 | 4 |
+------+-------+
20 rows in set (0.00 sec)
mysql>
mysql> drop table testscore;
Query OK, 0 rows affected (0.00 sec)
Related examples in the same category