欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL获取第2大值的记录:获取第二高薪水(MySQL)

程序员文章站 2022-03-04 23:34:28
编写一个 SQL 查询,获取 Employee表中第二高的薪水(Salary)。+----+--------+| Id | Salary |+----+--------+| 1 | 100 || 2 | 200 || 3 | 300 |+----+--------+例如上述Employee表,SQL查询应该返回200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。+---------------------+| SecondH......

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

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

代码1:

# Write your MySQL query statement below
select (select Salary from Employee where Salary < (select Salary from Employee order by Salary DESC limit 1) order by Salary DESC limit 1) as SecondHighestSalary

代码2:

# Write your MySQL query statement below
select (select distinct Salary from Employee order by Salary DESC limit 1,1) as SecondHighestSalary
# select (select distinct Salary from Employee order by Salary DESC limit 1 offset 1) as SecondHighestSalary

代码3:

# Write your MySQL query statement below
select ifnull((select distinct Salary from Employee order by Salary DESC limit 1,1), NULL) as SecondHighestSalary
# select ifnull((select distinct Salary from Employee order by Salary DESC limit 1 offset 1), NULL) as SecondHighestSalary

笔记:

代码3是常见模板。不过,似乎IFNULL(([SQL Query Set]), NULL)是多余的。就目前看来,更像是“画蛇添足”:一个 SQL Query Set 只有 非NULL NULL 两种情况。

本文地址:https://blog.csdn.net/qq_21264377/article/details/107924737

相关标签: Geek 逻辑 sql