Skip to content

Commit 71dce75

Browse files
Added Rank Scores
1 parent 0097a80 commit 71dce75

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Rank Scores
3+
https://leetcode.com/problems/rank-scores/
4+
5+
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.
6+
7+
+----+-------+
8+
| Id | Score |
9+
+----+-------+
10+
| 1 | 3.50 |
11+
| 2 | 3.65 |
12+
| 3 | 4.00 |
13+
| 4 | 3.85 |
14+
| 5 | 4.00 |
15+
| 6 | 3.65 |
16+
+----+-------+
17+
For example, given the above Scores table, your query should generate the following report (order by highest score):
18+
19+
+-------+---------+
20+
| score | Rank |
21+
+-------+---------+
22+
| 4.00 | 1 |
23+
| 4.00 | 1 |
24+
| 3.85 | 2 |
25+
| 3.65 | 3 |
26+
| 3.65 | 3 |
27+
| 3.50 | 4 |
28+
+-------+---------+
29+
Important Note: For MySQL solutions, to escape reserved words used as column names, you can use an apostrophe before and after the keyword. For example `Rank`.
30+
*/
31+
32+
-- Solution 1
33+
SELECT Scores.Score, t3.Rank
34+
FROM Scores JOIN (
35+
select Score, (@inc := @inc + 1) as "Rank"
36+
FROM (
37+
SELECT Score as Score
38+
FROM Scores
39+
GROUP BY Score
40+
ORDER BY Score DESC
41+
) AS t1 CROSS JOIN (SELECT @inc := 0 ) as t2
42+
) as t3 ON Scores.Score = t3.Score
43+
ORDER BY t3.Rank ASC
44+
45+
46+
-- Solution 2
47+
-- Set two variables, one to keep the previous Score and other to keep the current Rank
48+
SELECT Score,
49+
@curr := CASE WHEN @previous = (@previous := Score) THEN
50+
CAST(@curr AS SIGNED INTEGER)
51+
ELSE
52+
CAST(@curr + 1 AS SIGNED INTEGER)
53+
END AS "Rank"
54+
FROM Scores, (SELECT @curr := 0, @previous := -1) as t1
55+
ORDER BY SCORE DESC
56+

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ To run a specific problem in your console, go to the file test, add the call to
8181
### Databases
8282
| Problems | Level | Link |
8383
|-|-|-|
84+
| [Rank Scores](/LeetcodeProblems/Databases/Rank_Scores.sql) | Medium | https://leetcode.com/problems/rank-scores/ |
8485
| [Consecutive Numbers](/LeetcodeProblems/Databases/Consecutive_Numbers.sql) | Medium | https://leetcode.com/problems/consecutive-numbers |
8586
| [Department Highest Salary](/LeetcodeProblems/Databases/Department_Highest_Salary.sql) | Medium | https://leetcode.com/problems/department-highest-salary |
8687
| [Exchange Seats](/LeetcodeProblems/Databases/Exchange_Seats.sql) | Medium | https://leetcode.com/problems/exchange-seats |

0 commit comments

Comments
 (0)