0

I am trying to insert a value and calculating the value that i inserted into one column.

the example, basically I have one table with 3 column on it, id, amount, total:

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

expected result:

every time a new amount value is entered, I want the value in column total to be added with that value

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

is it ok to accumulate the negative value? and, anyone can correct my query? thank you

1 Answer 1

1

I recommend against doing this, and I instead suggest just using SUM as an analytic function:

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

The logic behind this answer is that your rolling sum total is derived, and not original, data. Therefore, it is better to just compute it on the fly when you need it, rather than storing it.

If you really want to insert the correct total during a single insert, you may try:

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();
Sign up to request clarification or add additional context in comments.

6 Comments

can you explain why against?
The rolling sum is derived data, and in general it should probably not be stored in your table.
what if i still want to store the value into table? do you have a solution for it?
@CodeOn I gave you an option using INSERT INTO ... SELECT.
the insert query with select will got error when there's no row before
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.