Nth Highest Salary Problem
Description
LeetCode Problem 177.
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 |
+------------------------+
MySQL Solution
1
2
3
4
5
6
7
8
9
10
11
12
create function getNthHighestSalary(N int) returns int
begin
return (
select distinct salary as 'getNthHighestSalary(2)'
from (
select salary,
dense_rank() over(order by salary desc) as rnk
from employee
) sal_rnk
where rnk = n
);
end
LeetCode Database - Medium
LeetCode 177
LeetCode 178
LeetCode 180
LeetCode 184
LeetCode 534
LeetCode 550
LeetCode 570
LeetCode 574
LeetCode 578
LeetCode 580
LeetCode 585
LeetCode 602
LeetCode 608
LeetCode 612
LeetCode 614
LeetCode 626
LeetCode 1045
LeetCode 1070
LeetCode 1077
LeetCode 1098
LeetCode 1107
LeetCode 1112
LeetCode 1126
More LeetCode Database
MySQL Tutorials