If I understood what you are trying to do, you need the trigger on DELETE as well. It would be something like this - I have not tested the code other than to see if it compiles:CREATE TRIGGER [dbo].[x_trigger1]ON [dbo].[TableB]FOR INSERT, UPDATE, DELETEAS;WITH cte1 AS( SELECT JobId FROM INSERTED UNION SELECT JobId FROM DELETED),cte2 AS ( SELECT c.JobId, SUM(b.linecost) AS TotalCost FROM TableB b INNER JOIN cte1 c ON c.JobId = b.JobId GROUP BY c.JobId)MERGE TableA aUSING cte2 c ON c.JobId = a.JobIdWHEN MATCHED THEN UPDATE SET a.totalcost = c.totalcostWHEN NOT MATCHED BY TARGET THEN INSERT (JobId, TotalCost) VALUES (c.JobId, c.TotalCost)WHEN NOT MATCHED BY SOURCE THEN DELETE;GO
Instead of having a table updated constantly, you could create a view with the sums. However, it is a trade-off. If the table is small but frequently updated, a view would be better. If the table is large and frequently queried, a trigger would be better.