~고군분투 인생살이~

[196] Delete Duplicate Emails 본문

SQL/LEETCODE

[196] Delete Duplicate Emails

소금깨 2022. 5. 28. 01:20

1. 문제 설명

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| email       | varchar |
+-------------+---------+
id is the primary key column for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.

 

Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest id. Note that you are supposed to write a DELETE statement and not a SELECT one.

After running your script, the answer shown is the Person table. The driver will first compile and run your piece of code and then show the Person table. The final order of the Person table does not matter.

The query result format is in the following example.

 

Example 1:

Input: 
Person table:
+----+------------------+
| id | email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Output: 
+----+------------------+
| id | email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+
Explanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1.

2. 문제 풀이

  • SELECT문이 아닌 DELETE문을 이용해서 쿼리 짜기.
  • 가장 작은 ID값을 가지는 하나의 고유한 이메일만 테이블에 남기기
    • 중복 이메일은 삭제한다.

3. 정답 

# 서브쿼리
DELETE 
FROM person
WHERE Id NOT IN (SELECT sub.min_id
			FROM (SELECT email, min(id) AS min_id
                	FROM person
                        GROUP BY email) sub)

 

두번째 풀이

with temp as (
    select email,
            min(id) as min_id
    from person
    group by email) -- 각 email별 min_id 확인 
    
delete 
from person
where id not in (select min_id
                from temp)

 

'SQL > LEETCODE' 카테고리의 다른 글

[STUDY_PALN] DAY1  (0) 2022.06.04
[177] Nth Highest Salary  (0) 2022.06.03
[180] Consecutive Numbers  (0) 2022.05.29
[185] Department Top Three Salaries  (0) 2022.05.26
[184] Department Highest Salary  (0) 2022.05.22
Comments