1. 程式人生 > 其它 >【SQL】LeetCode-Duplicate Emails

【SQL】LeetCode-Duplicate Emails

技術標籤:SQL

LeetCode 182:Duplicate Emails

【Description】

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:
在這裡插入圖片描述
Note: All emails are in lowercase.

【Solution】

Personal solution:

select distinct p1.Email
from Person p1,
Person p2 where p1.Email=p2.Email and p1.Id!=p2.Id

Reference solution:
1.Duplicated emails existed more than one time. We can build a temp table and count the times each email exists, and then get the duplicated emails.

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

2.A more common used way to add a condition to a GROUP BY is to use the HAVING clause, which is much simpler and more efficient.

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