分析:该题为排名题,有时排名会分为3种情况,比如工资300,200,200,100
不同实际场景对应的排名不同,可排成1-2-3-4,1-2-2-3,1-2-2-4这3种情况。
解法1:用对salary进行排名,再用Limit取第n-1名,注意Limit不能直接用N-1,去取。Limit(N,M)表示从N+1行开始取M行。
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set N=N-1;
RETURN (
select distinct salary
from Employee
order by salary desc
limit N,1
);
END
解法2:笛卡尔积连接形式,将两表拼合,以表1每个salary分组,计数每个salary小于表2去重后的salary个数,当数量等于N时输出。
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
ifnull(
(select distinct e1.salary
from Employee e1,Employee e2
where e1.salary<=e2.salary
group by e1.salary
having count(distinct e2.salary)=N),null
)
);
END
解法3:子查询,跟上面的思路差不多
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
select distinct e.salary
from Employee e
where (
select count(distinct salary) from Employee where e.salary<=salary
)=N
);
END
解法4:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
SELECT
DISTINCT salary
FROM
(SELECT
salary, @r:=IF(@p=salary, @r, @r+1) AS rnk, @p:= salary
FROM
employee, (SELECT @r:=0, @p:=NULL)init
ORDER BY
salary DESC) tmp
WHERE rnk = N
);
END