题目描述 编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。 +----+--------+| Id | Salary |+----+--------+| 1 | 100 || 2 | 200 || 3 | 300 |+----+--------+ 例如上述 Employee 表,SQL查询应该返回
题目描述
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
分析
select distinct salary from Employee order by salary desc limit 1,1 就可以,但是输不出null,所以外面再加一层 select (select distinct salary from Employee order by salary desc limit 1,1) as SecondHighestSalary ;
当Employee表里只有一条数据时,内层SQL语句查询不到数据,其返回结果是空,而外层SQL的作用是把内层的查询结果赋值给SecondHighestSalary.
贴出代码
select (select distinct salary from Employee order by salary desc limit 1,1) as SecondHighestSalary ;