SQL Leetcode: 177. Nth Highest Salary
177. Nth Highest Salary
Medium
599451Add to ListShare
Write a SQL query to get the nth highest salary from the Employee
table.
+----+--------+
| 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
.
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
- Using Correlated Subquery
CREATE FUNCTION getNthHighestSalary(N INT)
RETURNS INT
BEGIN
RETURN (
SELECT
Salary as getNthHighestSalary
from Employee e1
where N-1 = (Select COUNT(DISTINCT salary) from employee e2
WHERE e2.salary > e1.salary)
UNION
Select null
limit 1
);
END
2. Using DENSE_RANK()
CREATE FUNCTION getNthHighestSalary(N INT)
RETURNS INT
BEGIN
RETURN (
WITH CTE AS (
SELECT
Salary,
DENSE_RANK() OVER (ORDER BY SALARY DESC) as rank_salary
from Employee
)
SELECT distinct SALARY AS getNthHighestSalary
FROM CTE
WHERE rank_salary = N
UNION
Select null
limit 1
);
END