Postgresql求和匹配id数量并删除重复行

问题描述 投票:0回答:1

我有一个包含 id、item_id 和 qty(数量)列的表。我想“合并/组合”与 item_id 匹配的行。当我这样做时,我想要

SUM
每个 item_id 的数量更新一行并删除其他行。我找到了this解决方案,但我希望有一个单一的事务解决方案(我应该将它放在过程或函数中吗?)。我正在查看
MERGE
函数,但我无法弄清楚当我们有匹配时如何运行更新和删除,在我看来,它是用于合并两个表的。我确信一定有办法做到这一点,但这似乎超出了我的掌握范围。

原始数据集 enter image description here

交易方式取自上一个链接。

UPDATE test t
SET qty = s.qty
FROM (SELECT MIN(id) id, SUM(qty) qty
 FROM test
 GROUP BY item_id) s
 WHERE s.id = t.id

DELETE FROM test t1
WHERE t1.id > (SELECT MIN(t2.id)
           FROM test t2
          WHERE t2.item_id = t1.item_id)

第一笔交易后的结果。 enter image description here

第二次也是最后一次交易后的结果。这是我很满意的一个结果。 enter image description here

postgresql
1个回答
0
投票

您的结果与您的数据不符。

另外,请勿在此处发布屏幕截图。

您可以使用更新/返回 CTE 在一条语句中实现此目的:

with newrecs as (
  select item_id, min(id) as id, sum(qty) as qty
    from test
   group by item_id
), updates as (
  update test t
     set qty = n.qty
    from newrecs n
   where (n.id, n.item_id) = (t.id, t.item_id)
  returning t.id
)
delete from test where id not in (select id from updates);

工作小提琴

© www.soinside.com 2019 - 2024. All rights reserved.