LeetCode 178. Rank Scores (SQL Solutions)

This is a LeetCode medium-level SQL problem, but if you have a strong understanding of window functions, this question will be quite easy for you. In this post, I will be solving this question using various approaches. So, let’s get started.

Rank Scores Question

Table: Scores

Column NameType
idint
scoredecimal

id is the primary key (column with unique values) for this table.
Each row of this table contains the score of a game. Score is a floating point value with two decimal places.

Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:

The scores should be ranked from the highest to the lowest.
If there is a tie between two scores, both should have the same ranking.
After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.
Return the result table ordered by score in descending order.

The result format is in the following example.

Example 1:

Input:
Scores table:

idscore
13.50
23.65
34.00
43.85
54.00
63.65

Output:

scorerank
4.001
4.001
3.852
3.653
3.653
3.504

The Solutions

Solution 1: Dense Rank Approach

SELECT score, DENSE_RANK() OVER(ORDER BY score DESC) AS 'rank' FROM  scores

Explanation – here we just have to use dense rank function on score column and order should be descending as per the question. Note. make sure this rank alias in single quotes or double quotes.

Solution 2: Subquery Approach

select s.Score, l.Rank 
from Scores s
left join (
    select Score, row_number() over (order by Score desc) as 'Rank' 
    from Scores 
    group by Score
) l on l.Score=s.Score
order by s.Score desc

Explanation:

Subquery – The subquery calculates the rank for each unique score in descending order using the ROW_NUMBER() function

Left Join and ordering  score in descending – Now, let’s perform the left join between the original “Scores” table (aliased as s) and the subquery results (aliased as l) based on the “Score” column. now we will get desire output.

Conclusion

I would say this is very easy question as per medium level what do you think friends. hope you understood the my explanation. don’t forget to visit this website for such question. do practice every day.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top