Hive/Sql

leetcode(sql)196. Swap Salary

2019-06-27  本文已影响0人  马路仔

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

Person

Id Email
1 john@example.com
2 bob@example.com
3 john@example.com

Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:

Id Email
1 john@example.com
2 bob@example.com

Note:Your output is the whole Person table after executing your sql. Use delete statement.(您的输出是执行sql之后的整个Person表。使用delete语句。)

DELETE p1
FROM
    Person as p1 JOIN Person as p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id;

通过在电子邮件列中将这个表与它自己连接起来,然后我们需要找到与其他记录具有相同电子邮件地址的较大id。所以我们可以像这样在WHERE子句中添加一个新的条件。因为我们已经得到了要删除的记录,所以我们可以最后将这个语句更改为DELETE

上一篇下一篇

猜你喜欢

热点阅读