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

前端 未结 2 729
小蘑菇
小蘑菇 2021-01-29 12:11

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

相关标签:
2条回答
  • 2021-01-29 12:18

    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

    0 讨论(0)
  • 2021-01-29 12:36

    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
    
    0 讨论(0)
提交回复
热议问题