Skip to main content

LeetCode 178. Rank Scores SQL Solution

Problem

LeetCode SQL Problem

  1. Rank Scores

Scores table

idscore
13.5
23.65
34
43.85
54
63.65

Solution - Dense_Rank Approach

  • The problem states that there should be no holes between ranks so we're using Dense_Rank() to sort score from highest to lowest.
  • rank is a reverved word in MySQL so we need to escape it with an apostrophe before and after the keyword in order to use it as a column name.
SELECT score,
dense_rank() OVER (
ORDER BY score DESC
) AS 'rank'
FROM Scores
ORDER BY score DESC

Query Output

scorerank
41
41
3.852
3.653
3.653
3.54

Solution - Subquery Approach

  • A subquery is used to find out how many distinct score values are greater than the current score value. Adding that value by 1 is the current score's rank.
  • rank is a reverved word in MySQL so we need to escape it with an apostrophe before and after the keyword in order to use it as a column name.
SELECT s.score,
(
SELECT count(DISTINCT (ss.score)) + 1
FROM Scores ss
WHERE ss.score > s.score
) AS 'rank'
FROM Scores s
ORDER BY s.score DESC

Query Output

scorerank
41
41
3.852
3.653
3.653
3.54