[LeetCode] 查找重复的电子邮箱

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

示例sql

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

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

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

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

题解:

方法一:使用 GROUP BY和临时表
算法
重复的电子邮箱存在屡次。要计算每封电子邮件的存在次数,咱们能够使用如下代码。get

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

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

select Email from
(
  select Email, count(Email) as num
  from Person
  group by Email
) as statistic
where num > 1;

方法二:使用 GROUP BYHAVING 条件
GROUP BY 添加条件的一种更经常使用的方法是使用 HAVING 子句,该子句更为简单高效
因此咱们能够将上面的解决方案重写为:class

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

摘自:
https://leetcode-cn.com/problems/duplicate-emails/solution/cha-zhao-zhong-fu-de-dian-zi-you-xiang-by-leetcode/email

相关文章
相关标签/搜索