Labels

Wednesday, February 25, 2015

Duplicate Emails

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.

 Naive Way: 我先建一个Table(Email, count(*)), 然后在这个Table里找count(*) > 1的。


 SELECT Email  
 FROM   
 (SELECT Email, count(*) AS num  
 FROM Person  
 FROUP BY Email) E  
 WHERE num > 1;  

Improved Way: 不需要使用多余的subquery。

 SELECT Email from Person  
 GROUP BY Email  
 HAVING count(Email)>1;  

No comments:

Post a Comment