Mega Code Archive

 
Categories / MySQL / Select Clause
 

Advancing the rank only when values change

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> SET @rank = 0, @prev_val = NULL; Query OK, 0 rows affected (0.00 sec) mysql> SELECT @rank := IF(@prev_val=score,@rank,@rank+1) AS rank, @prev_val := score AS score FROM testscore ORDER BY sc ore DESC; +------+-------+ | rank | score | +------+-------+ |    1 |    10 | |    1 |    10 | |    2 |     9 | |    2 |     9 | |    2 |     9 | |    2 |     9 | |    2 |     9 | |    3 |     8 | |    3 |     8 | |    4 |     7 | |    4 |     7 | |    4 |     7 | |    4 |     7 | |    5 |     6 | |    5 |     6 | |    5 |     6 | |    5 |     6 | |    6 |     5 | |    7 |     4 | |    7 |     4 | +------+-------+ 20 rows in set (0.00 sec) mysql> mysql> drop table testscore; Query OK, 0 rows affected (0.00 sec)