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

yquaqz18  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(306)

如何删除与原始行重复的行,在哪里 unique_id 一样吗?
表为:

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尝试了一些查询,但我没有删除这两行。大多数情况下,我只管理了副本。

nkoocmlb

nkoocmlb1#

您可以使用窗口函数和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;
vshtjzan

vshtjzan2#

可以使用子查询:

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

相关问题