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 | +------------------------+
编写一个 SQL 查询,获取
Employee
表中第 n 高的薪水(Salary)。
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee
表,n = 2 时,应返回第二高的薪水 200
。如果不存在第 n 高的薪水,那么查询应返回 null
。
+------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+
140ms
1 CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 BEGIN 3 set N = N-1; 4 RETURN ( 5 # Write your MySQL query statement below. 6 select distinct Salary from Employee order by Salary desc limit N,1 7 ); 8 END
149ms
1 CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 BEGIN 3 set N = N-1; 4 RETURN ( 5 select distinct Salary as ‘getNthHighestSalary(2)‘ 6 from Employee 7 order by Salary desc 8 limit N, 1 9 ); 10 END
原文地址:https://www.cnblogs.com/strengthen/p/10145510.html
时间: 2024-10-03 00:13:56