SQL如何从另一个表中求和并插入另一个表中

时间:2016-01-02 22:59:39

标签: mysql sql database

现在我在Delphi应用中求值,然后将其插入SQL数据库中 但是当我插入新的ExpenseAmount时,我想要数据库加总并自动插入 我有2张桌子

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

我想为ExpenseAmount中的每个项目自动汇总ProjectsTable并将其插入ExpenseTotal ProjectsTable的{​​{1}}中 我想在SQL

Delphi全部执行此操作

2 个答案:

答案 0 :(得分:2)

您可以创建子查询,为每个项目分组费用金额,然后更新“项目”表。

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

答案 1 :(得分:2)

将此触发器添加到您的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

请勿忘记添加触发器 After Update After Delete 以更新ExpenseTotal