LeetCode-SQL练习题总结(MySQL实现)

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 表中第 高的薪水(Salary)。

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

例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 高的薪水,那么查询应返回 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 是唯一连续出现至少三次的数字。

+-----------------+
|
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值