一道算法题-第二高的薪水

147 阅读1分钟

第一次知道乐扣上竟然后又MySQL的算法题。本来以为会很容易,没想到还是有很多小技巧。

第二高的薪水

Employee 表:

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id 是这个表的主键。
表的每一行包含员工的工资信息。

编写一个 SQL 查询,获取 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null 。

查询结果如下例所示。

示例 1:

输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

示例 2:

输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null                |
+---------------------+

解题思路

代码位置:github.com/shidawuhen/…

主要利用两点,一是order by和limit,找到第二高的数据,二是使用sum,在不存在的情况下,会返回null。

需要关注的一点是,对salary做distinct操作,否则如果只有两个数据,且salary一致的话会报错。

代码

图片

select sum(salary) as SecondHighestSalary from 
(select salary  from 
 (select distinct(salary) as salary from Employee) as dsalary
order by salary desc limit 1,1) as t