Delete rows with duplicates on two fields

2019-09-15 01:10发布

问题:

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