1 Star 0 Fork 52

gentlhoo / 数据库SQL实战

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
75.查找重复的电子邮箱.md 2.08 KB
一键复制 编辑 原始数据 按行查看 历史
王鹏 提交于 2020-09-30 13:37 . 查找重复的电子邮箱

查找重复的电子邮箱

题目描述

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

Create table If Not Exists Person (Id int, Email varchar(255))
Truncate table Person
insert into Person (Id, Email) values ('1', 'a@b.com')
insert into Person (Id, Email) values ('2', 'c@d.com')
insert into Person (Id, Email) values ('3', 'a@b.com')

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

根据以上输入,你的查询应返回以下结果: +---------+ | Email | +---------+ | a@b.com | +---------+ 说明:所有电子邮箱都是小写字母。

答案

SELECT
    d.Name AS 'Department', e1.Name AS 'Employee', e1.Salary
FROM
    Employee e1
        JOIN
    Department d ON e1.DepartmentId = d.Id
WHERE
    3 > (SELECT
            COUNT(DISTINCT e2.Salary)
        FROM
            Employee e2
        WHERE
            e2.Salary > e1.Salary
                AND e1.DepartmentId = e2.DepartmentId
        )
;

题解

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

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

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

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

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

方法二:使用 GROUP BY 和 HAVING 条件 向 GROUP BY 添加条件的一种更常用的方法是使用 HAVING 子句,该子句更为简单高效。

所以可以将上面的解决方案重写为:

select Email
from Person
group by Email
having count(Email) > 1;
SQL
1
https://gitee.com/gentlhoo/database-sql-combat.git
git@gitee.com:gentlhoo/database-sql-combat.git
gentlhoo
database-sql-combat
数据库SQL实战
master

搜索帮助