LeetCode上的SQL练习题一共有十九道,题目网址:https://leetcode-cn.com/problemset/database/
本文将对其中的部分题做一个总结。
176.查询第二高的薪水:
编写一个 SQL 查询,获取 Employee
表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee
表,SQL查询应该返回 200
作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null
。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
方法一:
select (select distinct Salary from Employee order by Salary desc limit 1,1) as SecondHighestSalary;
# Salary数据有可能有重复的,所以要去重。
方法二:
select ifnull((select distinct Salary from Employee order by Salary desc limit 1,1),null) as SecondHighestSalary;
# 加个ifnull函数后,SQL语句的可能性更强。
177.查询第N高的薪水:
编写一个 SQL 查询,获取 Employee
表中第 n 高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee
表,n = 2 时,应返回第二高的薪水 200
。如果不存在第 n 高的薪水,那么查询应返回 null
。
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
代码:
# 创建存储函数:
create function getNthHighestSalary1(N INT)
returns int
deterministic
begin
declare x int;
set x = N-1;
return (select distinct Salary as NthHighestSalary from Employee1 order by Salary desc limit x,1);
end;
# 调用存储函数:
select getNthHighestSalary(2)
178.查询分数排名:
关于排名问题,详见:https://blog.youkuaiyun.com/qq_41080850/article/details/84858522
180.查询连续出现的数字:
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
例如,给定上面的 Logs
表, 1
是唯一连续出现至少三次的数字。
+-----------------+
|