Coding/SQL
[LeetCode-SQL 50] 196. Delete Duplicate Emails
kangplay
2025. 3. 11. 20:12
문제
https://leetcode.com/problems/delete-duplicate-emails/description

설명
중복된 이메일을 가진 회원을 삭제하고, 그 중 id가 제일 작은 회원은 남기는 문제이다.
group by 를 활용할 수도 있지만, 더 사용하기 유용한 윈도우 함수 rank를 사용하여 email로 partition을 한 후, id를 기준으로 정렬을 했을 때 순위가 2위 이상인 회원을 삭제하면 된다.
구현
# Write your MySQL query statement below
delete
from person
where id in (
select a.id as id
from (
select id, email, RANK() OVER (PARTITION BY email ORDER BY id ASC) as rn
from person
) a
where a.rn>1
)