177. Nth Highest Salary
Description
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 | +------------------------+
My Solution
Source Code
1
2
3
4
5
6
7
8
9
10
11
12
CREATE FUNCTION getNthHighestSalary(@N INT) RETURNS INT AS
BEGIN
RETURN (
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
OFFSET @N - 1 ROWS
FETCH NEXT 1 ROWS ONLY
);
END
Analysis
This one is basically the same as the 2nd Highest Salary problem, only this time instead of using a hardcoded value for the offset, we have a variable now. We get the unique salaries and sort them so they're in order. Then we select the one at offset N-1 since OFFSET is from the first row.