leetcode题解(SQL)(4)

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

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

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

思路一:

先去掉第一,再求最高, 同时解决null 的问题
select max(Salary) SecondHighestSalary
from Employee
where Salary <> (select max(Salary) from Employee );

思路二:

使用 limit 和 offset
select distinct 成绩  
from 成绩表
where 课程='语文'
order by 课程,成绩 desc
limit 1,offset 1

思路三:

降序排列再返回第二条记录可以得到第二大的值,后使用ifnull函数处理特殊情况
ifnull(a, b)  --- 如果不为空执行a,如果为空执行b    ===》 ifnull(第二步SQL, null)
select ifnull(
(select max(distinct 成绩) from 成绩表
where 成绩<(select max(成绩) from 成绩表 where 课程='语文')
and 课程='语文')
,null) as '语文课第二名成绩';

第二题:题目描述
编写一个 SQL 查询,查找所有至少连续出现三次的数字。

+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
+----+-----+

例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

思路:
1 将成绩表(score)复制3分,分别命名为a、b、c
2 我们需要找到这3个表中3个连续的学号,这个条件等价于a.学号 = b.学号-1 and b.学号 = c.学号-1
3 且a.成绩 = b.成绩 and b.成绩 = c.成绩
4 前面步骤已经将连续3人相等的成绩找出,现在用distinct去掉自连接产生的重复数。
select distinct a.成绩 as 最终答案
from score as a,
   score as b,
   score as c;
 where a.学号 = b.学号 - 1
   and b.学号 = c.学号 - 1
   and a.成绩 = b.成绩
   and b.成绩 = c.成绩;
发布了49 篇原创文章 · 获赞 77 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/a13352912632/article/details/104399149