今日刷题:
- 查询重复的邮箱
- 删除重复的邮箱
- 上升温度
1、查询重复的邮箱
解题思路:
- 此题有两种解法
- 第一种方法是对邮箱进行分组,然后求每个分组中记录条数大于1的记录,既为重复的邮箱
- 第二种方法是进行自连接,筛选出邮箱一样,但记录Id不一样的记录,最后再对邮箱去重(效率比较低)
SQL语句:
第一种:
select Email
from Person
group by Email
having count(Email) > 1
第二种:
select distinct p1.Email
from Person as p1 join Person as p2
where p1.Email = p2.Email and p1.Id != p2.Id
2、删除重复的邮箱
解题思路:
- 此题也有两种解法
- 第一种是运用自连接,查询出邮箱相同但Id大的记录,最后再删除
- 第二种是先分组查询出相同邮箱当中最小的Id记录,然后再用嵌套查询的方式查询该表中的所有记录是否在最小Id记录表中,不在当中则为重复的邮箱且Id大的记录,最后删除
SQL语句:
第一种:
delete p1
from Person as p1 join Person as p2
where p1.Email = p2.Email and p1.Id > p2.Id
第二种:
delete from Person
where Id not in (
select id from (
select Min(id) as id
from Person as p
group by p.Email
)
as temp
)
3、上升的温度
解题思路:
- 此题主要是用DATEDIFF()确定前一天的记录
SQL语句:
SELECT w2.Id
FROM Weather w1, Weather w2
WHERE DATEDIFF(w2.RecordDate, w1.RecordDate) = 1
AND w1.Temperature < w2.Temperature