此SQL查询不会执行。有人可以给出正确的语法吗?
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
我想更新类型为38 PTEmpID
匹配的类型42。另外加PTAmount
。
修改:每个PTEmpID
始终有38行和42行。所以我只想添加38到42 PTEmpID
匹配。整个表就是。
答案 0 :(得分:3)
此查询存在三个问题:
请改为尝试:
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
SUM()将确保从子查询中获得至少0的结果,如果有多个结果,则在将它们添加到ptm.PTAmount之前将它们相加。
此外,您并不真正需要表别名。由于子查询的PayrollTotals别名为pts,因此您可以直接通过名称引用更新的表:
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