0

I try to handle this situation in a PostgreSQL database. I insert data to a table called "Invoice" by programming:

invoice_id    account_id    amount  current 
    1            a2322        3      null
    2            a2322       10      null
    3            b4354        1      null
    4            c8099        2      null
    5            a2322        4      null
    6            b4354       -5      null

so, when a new record is inserted, I want to update the current field with the sum of amounts like this:

invoice_id    account_id    amount  current 
    1            a2322        3      null
    2            a2322       10      null
    3            b4354        1      null
    4            c8099        2      null
    5            a2322        4      null
    6            b4354       -5      null
    7            a2322        4      result(sum of amount: 21)
    8            b4354        3      result(sum of amount: -1)

Can I do that inside PostgreSQL without programming?

2 Answers 2

2

You can do this in a trigger AFTER INSERT OR UPDATE OR DELETE that runs FOR EACH STATEMENT. This is programming too, albeit not on the client side.

In the trigger you can calculate the sums like this (assuming that invoice_id is serial):

INSERT INTO invoice
   (account_id, amount, current)
SELECT account_id, sum(amount), 'result'
FROM invoice
WHERE current IS NULL
GROUP BY account_id
HAVING count(*) > 1
ON CONFLICT (account_id, current)
DO UPDATE
   SET amount = EXCLUDED.amount;

This requires a UNIQUE constraint on (account_id, current) and makes use of the fact that unique constraints allow “duplicate” as long as NULLs are incolved.

Sign up to request clarification or add additional context in comments.

Comments

0

This is not technically a direct answer to your question. But what you want is a running number. You may not need to store that info. It can be calculated on the fly:

SELECT *, SUM(amount) OVER(ORDER BY invoice_id) AS running_total;

This way, you won't need to worry about reconciliation and/or update errors. Especially if you later need to update the quantity, the running total will be all messed up, with SUM() OVER(), it will always be consistent.

Comments

Your Answer

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