gpt4 book ai didi

sql - 如何合并表 postgresql 中的两行?

转载 作者:行者123 更新时间:2023-11-29 13:00:25 28 4
gpt4 key购买 nike

通常我不会问这个问题,但是我有一些独特的情况,我在如何去做时遇到了麻烦。

我有一个表 A 如下:

uniqueid , itemid, quantity, selected
1 2455 10 TRUE
2 7458 50 FALSE
3 58494 20.6 FALSE
4 2455 20 TRUE

我需要编写一个组合函数,它获取相同部分的 TRUE 行并将它们组合成一行(使用更新的 quantity)。

意思是我想得到:

uniqueid , itemid, quantity, selected
1 2455 30 FASLE
2 7458 50 FALSE
3 58494 20.6 FALSE/TRUE (doesn't matter)

或者:

uniqueid , itemid, quantity, selected
2 7458 50 FALSE
3 58494 20.6 FALSE
4 2455 30 FALSE/TRUE (doesn't matter)

我的函数没有任何参数...我需要一些可以识别和处理所选行的方法。首先我想到了:

CREATE OR REPLACE FUNCTION func1()
RETURNS void AS
$BODY$
declare
ROW RECORD
begin
for ROW in select * from A where selected
LOOP
do combine code
end loop;
end;
$BODY$
LANGUAGE plpgsql VOLATILE

然而,这段代码将不起作用,因为每次合并两行后,两行就变成了一行。在上面的示例中,循环将生成两次迭代,但我只需要 1 次迭代。只需要 1 个组合操作。

我只需要帮助如何获得函数的结构 - 循环?如果?如何保存行?无需编写合并代码。

为了简化假设只有两行selectedTRUE

注意:func1 应该将新状态保存A

最佳答案

一个简单的解决方案是在联合中执行此操作 - 在这种情况下,selected = false 有多少行也无关紧要:

select min(uniqueid) as uniqueid,
itemid,
sum(quantity) as quantity,
false as selected
from a
where selected
group by itemid
union all
select uniqueid,
itemid,
quantity,
selected
from a
where not selected
order by 1;

编辑在明确表要修改后。

您可以使用数据修改 CTE 来完成此操作。在第一步中更新数量总和,在第二步中删除不再需要的行:

with updated as (
-- this updates the lowest uniqueid with the total sum
-- of all rows. If you want to keep/update the highest
-- uniqueid change the min() to max()
update a
set quantity = t.total_sum,
selected = false
from (
select min(uniqueid) as uniqueid,
itemid,
sum(quantity) as total_sum
from a
where selected
group by itemid
) t
where t.uniqueid = a.uniqueid
returning a.uniqueid
)
-- this now deletes the rows that are still marked
-- as "selected" and where not updated
delete from a
where selected
and uniqueid not in (select uniqueid from updated);

这假定 uniqueid 列确实是唯一的(例如,主键或定义了唯一索引/约束)。必须更改 selected 列的值才能使其正常工作。因此,在此过程中,selected 是否设置为 false 确实很重要。

关于sql - 如何合并表 postgresql 中的两行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32064502/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com