如何根据 3 个重复列删除 postgres sql 中的所有重复行,并保留最大和第二个最大日期值行

How to Delete all duplicate rows in postgres sql based on 3 duplicate columns and out of that keep max and second max date value rows

我有一个 table temp 它有 118507658 条记录。 我需要根据以下条件清理此 table。

如果三列 (dp_content_definition_id,dp_order,value_scope_id) 相同则删除这些记录但保留最大和第二个最大 entry_date 记录。

我写这个查询是为了查找记录。

select value_id ,content_definition_id ,order ,value_scope_id ,entry_date 
from temp ou
where (select count(*) from dp_values inr
where 
inr.content_definition_id = ou.content_definition_id 
and inr.order = ou.order 
and inr.value_scope_id = ou.value_scope_id ) > 3
order by content_definition_id,order ,value_scope_id
 limit 10000;

但我的第一个问题是,仅查找 10000 条记录就需要花费大量时间,而不知道查找所有记录需要多少时间。之后我不知道如何删除。

只需使用窗口化聚合函数,根据降序日期创建 ROW_NUMBER 并查找值 >=3 的那些。

select 
    select value_id ,content_definition_id ,order ,
    value_scope_id ,entry_date,
from
 (
    select value_id ,content_definition_id ,order ,
       value_scope_id ,entry_date,
       row_number(*)
       over (partition by content_definition_id ,order ,value_scope_id 
             order by entry_date desc ) as rn
    from temp ou
 ) dt
where rn >= 3
order by content_definition_id,order ,value_scope_id;

这将return要删除的数据。如果将条件更改为 where rn < 3,您将获得要保留的数据。根据百分比,将剩余的行 Insert/Select 放入新的 table 而不是删除旧行可能更有效。