編寫一個 SQL 查詢語句,獲取Employee
表中第n高的薪水(Salary)。spa
建立表和數據3d
Create table If Not Exists Employee (Id int, Salary int); Truncate table Employee; insert into Employee (Id, Salary) values('1', '100'); insert into Employee (Id, Salary) values('2', '200'); insert into Employee (Id, Salary) values('3', '300');
解法:code
1.對每個薪水A,只要大於等於A的不一樣薪水個數等於N便可。blog
所以子查詢求出大於等於A的不一樣薪水個數B。當B=A時,能得出結果。get
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN RETURN ( select distinct e1.Salary from Employee e1 where N = ( select count(distinct e2.Salary) from Employee e2 where e2.Salary >= e1.Salary ) ); END
2.直接用order by和limit。要注意的是,limit的偏移從0開始。第N個變成參數時,要改成N-1。it
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN declare p int default N - 1; RETURN ( select distinct salary from Employee order by salary desc limit p,1 ); END