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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-nncugalv-md.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

+----+---------+
| 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:github

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

Note: All emails are in lowercase.算法


编写一个 SQL 查询,查找 Person 表中全部重复的电子邮箱。微信

示例:app

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

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

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

说明:全部电子邮箱都是小写字母。code


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

算法:重复的电子邮件存在屡次。要计算每封电子邮件的存在时间,咱们能够使用如下代码。htm

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

以此做为临时表,咱们能够获得以下解决方案。blog

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;
相关文章
相关标签/搜索