如何添加特定的列当Postgres的插入值

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

我试图插入值和计算,我插入一列的值。

的例子中,基本上我有一个表与3上它柱,idamounttotal

id | amount | total
1 | 100 | 100 
2 | 200 | 300
3 | -100 | 200

预期结果:

每次进入一个新的amount值的时候,我想与该值被添加在列total

INSERT INTO public.tb_total_amount
(id, amount, total, create_time)
VALUES(1, 100, balance+amount, NOW());

是否确定累积负值?并且,任何人都可以纠正我的查询?谢谢

sql postgresql insert
1个回答
1
投票

我建议不要做这个,我只是用SUM作为分析函数,而不是建议:

SELECT
    id,
    amount,
    SUM(amount) OVER (ORDER BY id) total
FROM yourTable;

这个答案背后的逻辑是,你的滚动和total导出,而不是原始数据。因此,最好是只计算它在飞行时,你需要它,而不是将其存储。

如果你真的想插入一个插入过程中正确的总,您可以尝试:

INSERT INTO public.tb_total_amount (amount, total, create_time)
SELECT
    100,
    (SELECT COALESCE(amount, 0) FROM public.tb_total_amount
     ORDER BY id DESC LIMIT 1) + 100,
    NOW();
© www.soinside.com 2019 - 2024. All rights reserved.