Write a SQL query to get the nth highest salary in the Employee table (Salary).
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, in the above Employee table, when n = 2, the second highest salary 200 should be returned. If there is no nth highest salary, then the query should return null.
+------------------------+
| getNthHighestSalary(2) |
+----------------- -------+
| 200 |
+------------------------+
Solution:
One, Mysql
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare m INT;
set m = n-1;
RETURN (
# Write your MySQL query statement below.
SELECT distinct Salary FROM Employee order by salary desc limit m,1
);
END
Index of Limit starts from 0
二、Oracle
CREATE FUNCTION getNthHighestSalary(N IN NUMBER) RETURN NUMBER IS
result NUMBER;
BEGIN
/* Write your PL/SQL query statement below */
select salary into result
from (
select salary,rank() over(order by salary desc) as rn from employee
)a
where rn = n;
RETURN result;
END;
Note that select requires parameters returned by into.