Write a SQL query to find all duplicate emails in a table named Person
.
+----+---------+ | Id | Email | +----+---------+ | 1 | [email protected] | | 2 | [email protected] | | 3 | [email protected] | +----+---------+
For example, your query should return the following for the above table:
+---------+ | Email | +---------+ | [email protected] | +---------+
Note: All emails are in lowercase.
编写一个 SQL 查询,查找
Person
表中所有重复的电子邮箱。
示例:
+----+---------+ | Id | Email | +----+---------+ | 1 | [email protected] | | 2 | [email protected] | | 3 | [email protected] | +----+---------+
根据以上输入,你的查询应返回以下结果:
+---------+ | Email | +---------+ | [email protected] | +---------+
说明:所有电子邮箱都是小写字母。
方法1:使用GROUP BY
和临时表
算法:重复的电子邮件存在多次。要计算每封电子邮件的存在时间,我们可以使用以下代码。
1 select Email, count(Email) as num 2 from Person 3 group by Email;
| Email | num | |---------|-----| | [email protected] | 2 | | [email protected] | 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 BY
和HAVING
条件
向a添加条件的一种更常用的方法GROUP BY
是使用该HAVING
子句,这更简单,更有效。
所以我们可以重写上面的解决方案。
1 select Email 2 from Person 3 group by Email 4 having count(Email) > 1;
原文地址:https://www.cnblogs.com/strengthen/p/9721024.html
时间: 2024-10-09 02:13:04