https://leetcode.com/problems/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 | +------------------------+


1 Create table If Not Exists Employee (Id int, Salary int); 2 Truncate table Employee; 3 insert into Employee (Id, Salary) values ('1', '100'); 4 insert into Employee (Id, Salary) values ('2', '200'); 5 insert into Employee (Id, Salary) values ('3', '300'); 6 7 CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 8 BEGIN 9 DECLARE M INT; 10 SET M = N - 1; 11 RETURN ( 12 # Write your MySQL query statement below. 13 SELECT 14 (SELECT Salary 15 FROM Employee 16 ORDER BY Salary DESC 17 LIMIT M, 1) AS getNthHighestSalary 18 ); 19 END
本文介绍了一种使用SQL查询获取指定排名薪资的方法。通过创建函数getNthHighestSalary,可以返回Employee表中第N高的薪资。如果不存在该排名的薪资,则返回空值。
303

被折叠的 条评论
为什么被折叠?



