176. 第二高的薪水
链接: 题目地址.
SQL架构
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
思路
- 查询出排名第二高:使用 limit 1,1 或者 查询不是 max 的 max(即第二名)
关键点
- 多数据使用 distinct 去重
- limit1,1:offset 为 1(即从第二行记录开始),总共检索 1 行。
limit n = limit 0,n
lifnull(expr1,expr2)
:如果不是 null,返回 expr1;为 null,返回 expr2
代码
MySQL Code:
select ifnull((select distinct Salary from Employee order by Salary desc limit 1,1),null) as SecondHighestSalary
196. 删除重复的电子邮箱
题目描述
SQL架构
编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
提示:
执行 SQL 之后,输出是整个 Person 表。
使用 delete 语句。
关键点
- 注意进行 delete 操作的查询时,不能同时动态更新表,需要在操作外面套一层查询。否则会报错:
You can't specify target table 'Person' for update in FROM clause
。
代码
MySQL Code:
-- 方法 1:
delete from Person where Id not in (
select Id from (
select min(Id) as Id from Person group by Email
) t
)
-- 方法 2:
delete p1 from person p1, person p2
where p1.email = p2.email and p1.id > p2.id
197. 上升的温度
题目描述
SQL架构
表 Weather
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id 是这个表的主键
该表包含特定日期的温度信息
编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id 。
返回结果 不要求顺序 。
查询结果格式如下例:
Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
Result table:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)
关键点
- 使用
datediff(date1,date2)
函数,确认前后日期。
代码
MySQL Code:
select b.id from Weather a inner join Weather b on
a.Temperature < b.Temperature and datediff(b.recordDate,a.recordDate)=1