编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

解法一:1.找出最高薪水,2.找出只低于第一的最高薪水(第二高)
select max(salary) as SecondHighestSalary from employee where salary<(select max(salary) from employee)
解法二: 不同解法一的局限,这个解法更改LIMIT后面的数字把可以找出第N高的薪水,
select if(count(salary)>1,min(salary),null) as SecondHighestSalary
from (select salary from employee group by salary ORDER BY salary desc limit 2) as t;
解法三:使用函数IFNULL(),同样的 LIMIT N,1 中的N可以更改为任意数字
select IFNULL((select salary from employee group by salary order by salary desc limit 1,1),null)
as SecondHighestSalary
本文介绍如何使用SQL查询从Employee表中获取第二高的薪水。提供了三种不同的解决方案,包括找出最高薪水后查找次高薪水,使用LIMIT和IFNULL函数进行查询。
373

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



