Delete rows with duplicates on two fields

非 Y 不嫁゛ 提交于 2019-12-12 04:44:06

问题


I need to delete duplicated values of this table:

+----+-------+-------------+---------+
| id | name  | description | surname |
+----+-------+-------------+---------+
| 1  | Peter | Member      | Hitsh   |
| 2  | James | Member      | Tach    |
| 3  | Mary  | Member      | Popims  |
| 4  | Peter | Member      | Hitsh   |
+----+-------+-------------+---------+

I would want to remove all the duplicated values with the same name and surname.


回答1:


To keep the row with the smallest id for every set of duplicates on (name, surname):

DELETE FROM tbl
USING (
   SELECT id, row_number OVER (PARTITION BY name, surname ORDER BY id) As rn
   FROM   tbl
   ) del
WHERE  tbl.id = del.id
AND    del.rn > 1;

Assuming id to be unique.

Very similar question today:
Delete all rows but one with the greatest value per group



来源:https://stackoverflow.com/questions/22204369/delete-rows-with-duplicates-on-two-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!