[LeetCode] 177. Nth Highest Salary

Problem

Write a SQL query to get the nth highest salary from the Employee table.

1
2
3
4
5
6
7
+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

1
2
3
4
5
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

Explanation

  1. We can get the MAX salary of Employee E1 WHERE E2.Salary is greater than E1.Salary and COUNT(DISTINCT(E2.Salary)) is N-1.

Solution

1
2
3
4
5
6
7
8
9
10
11
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      # Write your MySQL query statement below.
      SELECT MAX(e1.Salary)
      FROM Employee e1
      WHERE N-1 = (SELECT COUNT(DISTINCT e2.Salary)
                  FROM Employee e2
                  WHERE e2.salary > e1.salary)
  );
END