[문제]

Table: Person


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:

Explanation: john@example.com is repeated two times.

We keep the row with the smallest Id = 1.

 

 

[문제 링크]

https://leetcode.com/problems/delete-duplicate-emails

 


[문제 설명]

> 중복되는 행 지우기

 

 

[나의 풀이]

-- 3. id 최솟값만 남기고 행 삭제하기
DELETE 
FROM Person
WHERE id NOT IN 
        -- 2. id 최솟값만 출력하기
		(SELECT A.min_id
        FROM 
        -- 1. email별로 그룹화하고 id의 최솟값도 구하기
          (SELECT email, MIN(id) AS min_id
          FROM Person
          GROUP BY email) A)

[설명]

1. 이메일(email)별로 그룹화하고 아이디(id)의 최솟값도 구하기

SELECT email, MIN(id) AS min_id
          FROM Person
          GROUP BY email

출력결과

email min_id
john@example.com 1
bob@example.com 2

 

 

2. 아이디(id)의 최솟값만 출력하기

SELECT A.min_id
        FROM 
        -- 1. email별로 그룹화하고 id의 최솟값도 구하기
          (SELECT email, MIN(id) AS min_id
          FROM Person
          GROUP BY email) A

출력결과

min_id
1
2

 

 

3. 아이디(id)의 최솟값만 남기고 행 삭제하기

-- 3. id 최솟값만 남기고 행 삭제하기
DELETE 
FROM Person
WHERE id NOT IN 
        -- 2. id 최솟값만 출력하기
		(SELECT A.min_id
        FROM 
        -- 1. email별로 그룹화하고 id의 최솟값도 구하기
          (SELECT email, MIN(id) AS min_id
          FROM Person
          GROUP BY email) A)

출력결과

id email
1 john@example.com
2 bob@example.com

 

 

 

 

 

 

+ Recent posts