The common way of solving the classic SQL problem of ranking, involves a self join. I wish to present a different solution, which only iterates the table once, and provides the same output.
The ranking problem
Given a table with names and scores (e.g. students exams scores), add rank for each row, such that the rank identifies her position among other rows. Rows with identical scores should receive the same rank (e.g. both contenders got the silver medal).
Consider the following table (download score.sql):
mysql> select * from score; +----------+--------------+-------+ | score_id | student_name | score | +----------+--------------+-------+ | 1 | Wallace | 95 | | 2 | Gromit | 97 | | 3 | Shaun | 85 | | 4 | McGraw | 92 | | 5 | Preston | 92 | +----------+--------------+-------+ 5 rows in set (0.00 sec)
We wish to present ranks in some way similar to:
+----------+--------------+-------+------+ | score_id | student_name | score | rank | +----------+--------------+-------+------+ | 2 | Gromit | 97 | 1 | | 1 | Wallace | 95 | 2 | | 4 | McGraw | 92 | 3 | | 5 | Preston | 92 | 3 | | 3 | Shaun | 85 | 4 | +----------+--------------+-------+------+