【SQL】LeetCode-Duplicate Emails
阿新 • • 發佈:2021-01-24
技術標籤:SQL
LeetCode 182:Duplicate Emails
【Description】
Write a SQL query to find all duplicate emails in a table named Person.
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;