如何删除与原始行重复的行?

How delete duplicates rows with original?

如何删除与原始行重复的行,其中 unique_id 相同?

Table 是:

unique_id  col1   col2   col3
95         1       1      1
21         1       1      1
23         1       1      1
29         1       1      1
95         2       1      2

我想删除两行,其中 unique_id 相同。 A 尝试了一些查询,但我没有让我删除这两行。大多数情况下,我只管理了副本。

您可以使用 window 函数和 CTE:

with todelete as (
      select t.*, count(*) over (partition by unique_id) as cnt
      from t
     )
delete from todelete
    where cnt >= 2;

如果您想保留其中之一,可以改用 row_number()

with todelete as (
      select t.*, row_number() over (partition by unique_id) as seqnum
      from t
     )
delete from todelete
    where seqnum >= 2;

您可以使用子查询:

delete from t
where unique_id in (
  select unique_id from t group by unique_id having count(*) > 1
)