简体   繁体   中英

SQL How to sum from another table and insert in another table

For now I sum in Delphi app and then insert it in SQL database
but I want database to sum and insert automatically when I insert new ExpenseAmount
I have 2 tables

ProjectsTable (ProjectID, ProjectName, Cost, ExpenseTotal, CostRemaining)
ExpenseTable (ID, ProjectID, ExpenseAmount, ExpenseDate)

I want automatically sum ExpenseAmount for every single project in ProjectsTable and insert it in ExpenseTotal from ProjectsTable
I want to do that in SQL all out of Delphi

You can create a subquery grouping the expense amount for each project, and then updating the Projects table.

UPDATE ProjectsTable
SET ProjectsTable.ExpenseTotal = S1.ExpenseAmount
FROM ProjectsTable
INNER JOIN (SELECT ProjectID, SUM(ExpenseAmount) as ExpenseAmount
FROM ExpenseTable
GROUP BY ProjectID) as S1
ON ProjectsTable.ProjectID = S1.ProjectID

Add this trigger to your ExpenseTable

CREATE TRIGGER ExpenseSum AFTER INSERT ON ExpenseTable FOR EACH ROW
BEGIN
    UPDATE ProjectsTable P
    SET ExpenseTotal = 
    (SELECT SUM(ExpenseAmount) from ExpenseTable
    where ExpenseTable.ProjectID= P.ProjectID)
    where P.ProjectID = New.ProjectID;
END

Don't forget to add trigger After Update and After Delete to update ExpenseTotal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM