现在我在Delphi
应用中求值,然后将其插入SQL
数据库中
但是当我插入新的ExpenseAmount
时,我想要数据库加总并自动插入
我有2张桌子
ProjectsTable (ProjectID, ProjectName, Cost, ExpenseTotal, CostRemaining)
ExpenseTable (ID, ProjectID, ExpenseAmount, ExpenseDate)
我想为ExpenseAmount
中的每个项目自动汇总ProjectsTable
并将其插入ExpenseTotal
ProjectsTable
的{{1}}中
我想在SQL
Delphi
全部执行此操作
答案 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