Reputation: 12874
This SQL query does not execute. Can someone give the correct syntax?
UPDATE PayrollTotals ptm
SET PTAmount = PTAmount +
(SELECT pts.PTAmount FROM PayrollTotals pts WHERE pts.PTACID = 38
AND pts.PTAmount > 0
AND pts.PTEmpID= ptm.PTEmpID)
WHERE PTACID = 42
I want to update types 42 with types 38 where the PTEmpID
match. Also sum PTAmount
.
Edit: There will always be 38 and 42 row for each PTEmpID
. So I just want to add 38 to 42 where PTEmpID
match. The whole table that is.
Upvotes: 0
Views: 163
Reputation: 35404
Three problems with this query:
Try this instead:
UPDATE PayrollTotals SET PTAmount = PTAmount +
(SELECT SUM(pts.PTAmount) FROM PayrollTotals pts WHERE
pts.PTACID = 38
AND pts.PTAmount > 0
AND pts.PTEmpID = ptm.PTEmpID)
FROM
PayrollTotals AS ptm
WHERE
PTACID = 42
The SUM() will ensure that you get at least a 0 result from the subquery, and if there are multiple results, it will sum them before adding them to ptm.PTAmount.
Also, you don't really need the table alias. Since the subquery's PayrollTotals is aliased as pts, you can refer to the updated table directly by its name:
UPDATE PayrollTotals SET PTAmount = PTAmount +
(SELECT SUM(pts.PTAmount) FROM PayrollTotals pts WHERE
pts.PTACID = 38
AND pts.PTAmount > 0
AND pts.PTEmpID = PayrollTotals.PTEmpID)
WHERE
PTACID = 42
Upvotes: 3