为有牺牲多壮志,敢教日月换新天。

[SQL]LeetCode182. 查找重复的电子邮箱 | Duplicate Emails

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9721024.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Write a SQL query to find all duplicate emails in a table named Person.

+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+

For example, your query should return the following for the above table:

+---------+
| Email   |
+---------+
| a@b.com |
+---------+

Note: All emails are in lowercase.


编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

示例:

+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+

根据以上输入,你的查询应返回以下结果:

+---------+
| Email   |
+---------+
| a@b.com |
+---------+

说明:所有电子邮箱都是小写字母。


方法1:使用GROUP BY和临时表

算法:重复的电子邮件存在多次。要计算每封电子邮件的存在时间,我们可以使用以下代码。

1 select Email, count(Email) as num
2 from Person
3 group by Email;
| Email   | num |
|---------|-----|
| a@b.com | 2   |
| c@d.com | 1   |

以此作为临时表,我们可以得到如下解决方案。

1 select Email from
2 (
3   select Email, count(Email) as num
4   from Person
5   group by Email
6 ) as statistic
7 where num > 1
8 ;

方法2:使用GROUP BYHAVING条件

向a添加条件的一种更常用的方法GROUP BY是使用该HAVING子句,这更简单,更有效。

所以我们可以重写上面的解决方案。

1 select Email
2 from Person
3 group by Email
4 having count(Email) > 1;

 

posted @ 2018-09-28 21:27  为敢技术  阅读(356)  评论(0编辑  收藏  举报