sql 178. Score ranking

Write a SQL query to achieve the score rankings. If the two scores are identical, the two scores rank (Rank) the same. Note that in the bisecting a ranking should be the next consecutive integer values. In other words, there should be no "gap" between the ranking.

+ ---- + ------- +
| Id | Score |
+ ---- + ------- +
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+ ---- + ------- +
for example, according to the above given table scores, your query should return (by score from highest to lowest ):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+

SELECT Score, (SELECT count(DISTINCT score) FROM Scores WHERE score >= s.score) AS Rank FROM Scores s ORDER BY Score DESC ;

Here

SELECT count (DISTINCT score) FROM Scores WHERE score> = s.score is to find out is greater than the number of unique appearance scores that rank

Guess you like

Origin www.cnblogs.com/wangshaowei/p/11039309.html