MySQL to achieve ranking

0x01. Demand

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 table given 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    |
+-------+------+

SQL schema:

Create table If Not Exists Scores (Id int, Score DECIMAL(3,2))
Truncate table Scores
insert into Scores (Id, Score) values ('1', '3.5')
insert into Scores (Id, Score) values ('2', '3.65')
insert into Scores (Id, Score) values ('3', '4.0')
insert into Scores (Id, Score) values ('4', '3.85')
insert into Scores (Id, Score) values ('5', '4.0')
insert into Scores (Id, Score) values ('6', '3.65')

0x02. Address the needs of

Ranked roadmap is as follows:

  • First, the table in reverse order, as the first column.

  • Ranking the second column in Table calculated as follows:

    • Each number is larger than the calculated number from the sorted table, because the same will be repeated, so it is necessary to go heavy, heavier than their own to go after the big number is its ranking.
    • For example: 999998, ranking 98 calculation, need only count the number greater than or equal to a weight of 98, it is its ranking 2 is calculated.
  • The two tables together.

SQL statement is as follows:

SELECT 
    a.Score AS Score,
    (SELECT  COUNT(DISTINCT b.Score) FROM Scores b WHERE b.Score>=a.Score) AS Rank
From 
    Score  a
ORDER BY a.Score DESC;

ATFWUS --Writing By 2020–03–29

Published 162 original articles · won praise 182 · views 10000 +

Guess you like

Origin blog.csdn.net/ATFWUS/article/details/105183572