leetcode-178. Score ranking

  • topic

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')

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 |
±------±-----+

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/rank-scores
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

  • analysis

First, this is a sort, and then need to make changes to a sort of ranking, because the general ranking for the same elements in fact distinguishes the priorities, and this will affect the ranking of priorities, so we candistinctThis brought the order to eliminate the influence. And sort the records after the order though, but it also requires field ranking Rank (original table does not exist, so the need to useasTo be represented) indicated, and for each ranking method is generally used to obtain the values compared with each other.
See detailed analysis of the code.

  • Code
# Write your MySQL query statement below
#大前提下对score进行排序,再在结果的表中添加Rank字段
#Rank的确定要靠score值的比较来确定,所以要指定原表的两个别名s1,s2以方便比较
#利用关键字已去除重复score的影响(即order的影响)
select s1.Score , count(distinct(s2.Score)) as Rank from Scores s1, Scores s2
where s1.Score<=s2.Score group by s1.Id
order by Score desc;

Here Insert Picture Description
2019.12.15

Published 52 original articles · won praise 59 · views 6833

Guess you like

Origin blog.csdn.net/ataraxy_/article/details/103546617