标签:second 语句 tab asc 最大 select desc 存在 不用
描述
编写一个 SQL 查询,获取 Employee?表中第二高的薪水(Salary)?。
Id | Salary |
---|---|
1 | 100 |
2 | 200 |
3 | 300 |
例如上述?Employee?表,SQL查询应该返回?200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
SecondHighestSalary |
---|
200 |
解法一(MAX + 子查询)
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
where salary < (
SELECT MAX(Salary)
FROM Employee
)
解法二(limit + IFNULL + distinct)
select IFNULL((
select distinct e.Salary
from Employee e
order by e.Salary desc
limit 1,1
),null) as SecondHighestSalary
解法三(limit + distinct,其实可以不需要IFNULL!?)
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary
select IFNULL((
select s.Salary as SecondHighestSalary
from
(select distinct e.Salary
from Employee e
order by e.Salary desc
limit 1,1) s
order by s.Salary asc
limit 1
),null) as SecondHighestSalary
标签:second 语句 tab asc 最大 select desc 存在 不用
原文地址:https://www.cnblogs.com/wyp1988/p/12101160.html