Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

sql - Trigger to sum value of column of all rows and store in a column

I have two tables in oracle.

invoice(id_invoice, description, price)

product_invoice(id,id_invoice, description, price, quantity, final_price)

I want to do the the "sum" of the column of "final_price" with all the rows with the same "id_invoice" and store it in the table invoice. I'm trying using triggers but not working. Here's my trigger

create or replace NONEDITIONABLE TRIGGER updateukupno AFTER insert ON stavkaotpremnice FOR EACH ROW BEGIN
UPDATE invoice a
SET a.price = 
    (SELECT SUM(final_price) 
       FROM product_invoice
      WHERE id_invoice = a.id_invoice)
 WHERE a.id_invoice = :NEW.id_invoice;
END;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this type of logic is usually expressed incrementally:

UPDATE invoice i
    SET price = price + coalesce(:new.final_price, 0)) 
    WHERE i.id_invoice = :NEW.id_invoice;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...