LeetCode-SQL-three
2020-02-08 本文已影响0人
皮皮大
本文中主要是介绍LeetCode
中关于SQL
的练习题,从易到难,循序渐进。文中会介绍题目和尽可能多的解答方案
196-删除重复的电子邮箱
题目
编写一个 SQL 查询,来删除 Person
表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。下面是demo
答案
delete from Person
where Id not in ( -- 4. 删除不在查询结果中的值
select id from -- 2. 分组之后将相同的Email Id最小的选择出来
(select min(Id) as Id -- 最小Id
from Person
group by Email -- 1. 分组
)as temp -- 3. 建立临时表
);
-- delete+自连接
delete p1 -- 如果使用了别名,删除的时候需要将别名写在delete后面
from Person p1,
Person p2
where p1.Email=p2.Email
and p1.Id > p2.Id; -- 删除重复Id,并且保存最小的
197-上升的温度
题目
给定一个 Weather
表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id
image
本题中涉及到的知识点是datediff
函数,用来比较连个日期类型的差值
select w1.id as 'Id'
from weather w1
join weather w2 on datediff(w1.RecordDate, w2.RecordDate) = 1 -- 比较两个日期
and w1.temperature > w2.temperature; -- and是直接查询
select w1.id as 'Id'
from weather w1
join weather w2 on datediff(w1.RecordDate, w2.RecordDate) = 1 -- 比较两个日期
where w1.temperature > w2.temperature; -- where是在结果中进行筛选
关于日期的两个函数
- datediff(日期1,日期2)
得到的结果是两个日期相差的天数:日期1大,得到的是正数;日期1小,得到的是负数
- timestampdiff(时间类型, 日期1, 日期2)
正负号刚好和datediff
函数相反;第一个参数可以是
- day
- hour
- second