[SQL] [LeetCode] Challenge log 177

177. Nth Highest Salary

Use limit, offset, order by together


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 |
+------------------------+

Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set N = N-1;
RETURN (
# Write your MySQL query statement below.

select distinct salary
from Employee
order by salary desc
limit 1 offset N


);
END
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
-- alter
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set N=N-1;
RETURN (
# Write your MySQL query statement below.
select max(E.salary)
from Employee E
where E.salary not in (
select t.salary
from
(
select distinct A.salary
from Employee A
order by A.salary desc
limit N
) as t

)
);
END
0%