力扣SQL 第176题
题目:求第二高的薪水
employee表
id | salary |
---|---|
1 | 100 |
2 | 200 |
3 | 300 |
4 | 300 |
分析结果:查询结果应该最后返回的是200作为第二高的薪水。如果不存在则为null
【解题思路】
1:考虑到成绩可能有重复的值,所以我们第一就是使用distinct去重;
2:
思路一、可以先求出最大的值,然后再找出小于这个最大值的列即为第二高的薪水;
如下:
select max(distinct salary) from emplyee;
select max(distinct salary) from emplyee where salary < (select max(distinct salary) from emplyee);
思路二、使用limit和offset
limit n表示查询结果返回前N条数据;
offset n表示跳过n条数据; limit y offset x
分句表示查询结果跳过 x 条数据,读取前 y 条数据
如下:则表示跳过1条数据,获取前1条数据,就是第二条数据;
select distinct salary from emplyee order by salary desc limit 1 OFFSET 1;
走到这里,其实大体结果就出来了,那我们就需要考虑最后一步,没有第二高的薪水的时候为空;
3、没有的话为空;
ifnull(a,b)函数用于判断第一个表达式是否为 NULL,如果为 NULL 则返回第二个参数的值,如果不为 NULL
则返回第一个参数的值。
那最后的sql语句就是:看自己喜欢用那种方式了
select IFNULL((select distinct salary from emplyee order by salary desc limit 1 OFFSET 1),null) as '第二高的薪水';
select IFNULL((select max(distinct salary) from emplyee where salary < (select max(distinct salary) from emplyee)),null) as '第二高的薪水';