我有一个包含 id、item_id 和 qty(数量)列的表。我想“合并/组合”与 item_id 匹配的行。当我这样做时,我想要
SUM
每个 item_id 的数量更新一行并删除其他行。我找到了this解决方案,但我希望有一个单一的事务解决方案(我应该将它放在过程或函数中吗?)。我正在查看 MERGE
函数,但我无法弄清楚当我们有匹配时如何运行更新和删除,在我看来,它是用于合并两个表的。我确信一定有办法做到这一点,但这似乎超出了我的掌握范围。
交易方式取自上一个链接。
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)
您的结果与您的数据不符。
另外,请勿在此处发布屏幕截图。
您可以使用更新/返回 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);