返回介绍

solution / 0100-0199 / 0196.Delete Duplicate Emails / README_EN

发布于 2024-06-17 01:04:03 字数 3285 浏览 0 评论 0 收藏 0

196. Delete Duplicate Emails

中文文档

Description

Table: Person

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

 

Write a solution to delete all duplicate emails, keeping only one unique email with the smallest id.

For SQL users, please note that you are supposed to write a DELETE statement and not a SELECT one.

For Pandas users, please note that you are supposed to modify Person in place.

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 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.

Solutions

Solution 1

import pandas as pd


# Modify Person in place
def delete_duplicate_emails(person: pd.DataFrame) -> None:
  # Sort the rows based on id (Ascending order)
  person.sort_values(by="id", ascending=True, inplace=True)
  # Drop the duplicates based on email.
  person.drop_duplicates(subset="email", keep="first", inplace=True)
# Write your MySQL query statement below
DELETE FROM Person
WHERE id NOT IN (SELECT MIN(id) FROM (SELECT * FROM Person) AS p GROUP BY email);

Solution 2

# Write your MySQL query statement below
DELETE FROM Person
WHERE
  id NOT IN (
    SELECT id
    FROM
      (
        SELECT
          id,
          ROW_NUMBER() OVER (
            PARTITION BY email
            ORDER BY id
          ) AS rk
        FROM Person
      ) AS p
    WHERE rk = 1
  );

Solution 3

DELETE p2
FROM
  person AS p1
  JOIN person AS p2 ON p1.email = p2.email
WHERE
  p1.id < p2.id;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文