【问题标题】:How to remove duplicate rows in postgresql with condition?如何使用条件删除postgresql中的重复行?
【发布时间】:2021-01-12 05:41:47
【问题描述】:

我想删除条件为更新日期小于最大更新日期的重复行。但是,我无法删除它们。

我的尝试:

  SELECT * FROM (
  SELECT *,
  ROW_NUMBER() OVER(PARTITION BY order_code, customer_id, id, sign_date ORDER BY updated_at DESC) AS Row
  FROM fulfillment_bill_transactions WHERE active =1 AND transaction_type= 2
) dups
WHERE
dups.Row > 1

我的查询结果显示了更新日期最短的行,但不是所有更新日期,最长日期除外。

示例如下:

表 A:

ID Sign Date Customer id order code updated_at
A 2021/01/01 001 AB 2020/01/02
A 2021/01/01 001 AB 2020/01/03
A 2021/01/01 001 AB 2020/01/12
B 2021/01/03 002 LL 2020/02/02
B 2021/01/03 002 LL 2020/02/03
B 2020/01/03 002 LL 2020/02/04

想要的结果:

ID Sign Date Customer id order code updated_at
A 2021/01/01 001 AB 2020/01/12
B 2020/01/03 002 LL 2020/02/04

【问题讨论】:

  • 根据 OP 的描述,好像 OP 已经得到了你需要的数据?如果这是真的,那么只需将其插入新表然后删除旧表。
  • PARTITION BY order_code, customer_id, id, sign_date --> PARTITION BY id
  • 与您的问题无关,但是:Postgres 9.1 是no longer supported,您应该尽快计划升级。

标签: sql postgresql validation postgresql-9.1


【解决方案1】:

在 Postgres 中,如果您希望每组一行,那么我建议使用 distinct on。对于您提供的示例数据,这将是:

select distinct on (id) fbt.*
from fulfillment_bill_transactions fbt
order by id, date desc;

目前尚不清楚您的代码与该问题有什么关系。它是指不在样本数据中的列,并且问题中没有描述过滤条件。

【讨论】:

  • 嗨,戈登,感谢您的帮助,我已经更新了问题。现在应该更清楚了。
【解决方案2】:

如果要删除除最高更新日期之外的所有重复行,则可以使用以下查询:

delete FROM fulfillment_bill_transactions t 
 WHERE exists (select 1 from fulfillment_bill_transactions tt
                where tt.id = t.id
                  AND tt.updated_date > t.updated_date);

【讨论】:

  • 感谢您的帮助,但我试过了,剩下的那一行不是更新日期最高的那一行。看起来这个查询只比较两行。我已经更新了问题,希望您能提供帮助。谢谢。
  • 我已经更新了答案。请立即检查。
  • 它也不好用。我想通了: select * from ( SELECT *, ROW_NUMBER() OVER(PARTITION BY order_code, customer_id, id, sign_date ORDER BY updated_at DESC) AS Row FROMfulfillment_bill_transactions WHERE active =1 AND transaction_type= 2 ) dups where dups.Row > 1
猜你喜欢
  • 2022-07-18
  • 2021-12-16
  • 1970-01-01
  • 2020-10-14
  • 2019-09-23
  • 2018-06-15
  • 2016-08-16
  • 1970-01-01
  • 2016-08-30
相关资源
最近更新 更多