Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- Hackerrank
- medium
- 패스트캠퍼스
- 파이썬을활용한시계열데이터분석AtoZ올인원패키지Online
- 프리미엄
- lv.4
- 패캠챌린지
- 해커랭크
- 패스트캠퍼스후기
- 프로그래머스
- meidum
- HACKER_RANK
- easy
- RANK
- solvesql
- 파이썬을활용한시계열데이터분석
- 직장인자기계발
- row_number
- SQL
- 다시풀어보기
- Hard
- 시계열데이터분석
- recursive
- 어려웠음
- group by
- LeetCode
- SELF-JOIN
- join
- MySQL
- 직장인인강
Archives
- Today
- Total
~고군분투 인생살이~
[196] Delete Duplicate Emails 본문
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