当前位置:网站首页>LeetCode 178. Score ranking (MySQL)

LeetCode 178. Score ranking (MySQL)

2022-06-13 03:29:00 TRX1024

subject

Write a SQL Query to achieve score ranking .
If two scores are the same , Then two scores rank (Rank) identical . Please note that , The next rank after bisection should be the next consecutive integer value . let me put it another way , There should not be between ranks “ interval ”.
+----+-------+
| 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... Given above Scores surface , Your query should return ( Rank by score from high to low ):
+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+
Important note : about MySQL Solution , If you want to escape a reserved word used as a column name , You can use apostrophes before and after keywords . for example `Rank`


Their thinking :

External queries are arranged in descending order of scores , The sub query finds the number of scores greater than or equal to the current score , This number is the rank of the current score , If the same score and rank , use distinct duplicate removal .

Code :

select 
  Score, 
  (
    select 
      count(distinct Score) 
    from 
      Scores 
    where 
      Score >= a.Score
  ) as `Rank`
from 
  Scores a 
order by 
  Score desc

Expand :

mysql There are functions that provide automatic sorting in :dense_rank() over(),rank() over(),row_num() over().

Please move to the next step for specific usage and differences :mysql AutoSort function dense_rank() over()、rank() over()、row_num() over() Usage and difference

 

原网站

版权声明
本文为[TRX1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280529583397.html