Description

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.

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

For example, given the above Scores table, your query should generate the following report (order by highest score):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

Solutions

1. Count

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT DEFAULT N-1;
-- DECLARE M INT;
-- SET M=N-1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT ( SELECT DISTINCT Salary
      FROM Employee
      ORDER by Salary DESC
      -- LIMIT 1 offset M
      LIMIT M, 1
      )
  );
END

-- 14/14 cases passed (184 ms)
-- Your runtime beats 97.82 % of mysql submissions
-- Your memory usage beats 100 % of mysql submissions (0B)

2. Two Variables

SELECT
    Score,
    @rank := @rank + (@prev <> (@prev := Score)) Rank
FROM
    Scores,
    (SELECT @rank := 0, @prev := -1) init
ORDER BY Score DESC

-- 10/10 cases passed (271 ms)
-- Your runtime beats 96.58 % of mysql submissions
-- Your memory usage beats 100 % of mysql submissions (0B)

References

  1. 178. Rank Scores
  2. Simple, Short, Fast