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 ExpenseA
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
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