我有如下表格
CatID| Total_Amount | Amount_paying |IsCompleted
-----|--------------|---------------|------------
CA01 | 2000 | 1700 | 0
在此表中,我必须检查Total_Amount和amount_paying是否相同? 其中total_amount是固定的,amount_paying将在每个插入语句后获得最大化。
所以如果我插入一条记录
CatID| Total_Amount | Amount_paying |IsCompleted
-----|--------------|---------------|------------
CA01 | 2000 | 1700 | 0
CA01 | 2000 | 300 | 1
我支付300,所以Total_Amount = Amount_Paying和IsCompleted = 1
UPDATE tbl
SET is_completed = CASE WHEN SUM(amount_paying) = Total_Amount THEN 1 ELSE 0 END
WHERE tbl.branch_id =@branchid AND CatID=@catid
给予An aggregate may not appear in the set list of an UPDATE statement.
答案 0 :(得分:0)
如果数据库引擎在UPDATE
语句中允许相同的目标表:
UPDATE tbl
SET IsCompleted = IF((SELECT SUM(Amount_paying) FROM tbl WHERE CatID = 'CA01') >= Total_Amount, 1, 0)
WHERE CatID = 'CA01';
但是,例如,使用MySQL,您将获得Query Error: Error: ER_UPDATE_TABLE_USED
。
所以,下面应该有效:
UPDATE tbl AS t
JOIN (
SELECT
CatID,
SUM(Amount_paying) AS totalAP
FROM tbl
WHERE CatID = 'CA01'
GROUP BY CatID
) AS t2 ON (t2.CatID = t.CatID)
SET t.IsCompleted = IF(t2.totalAP >= t.Total_Amount, 1, 0)
WHERE t.CatID = 'CA01';
这是 demo fiddle 。
注意:在您自己的示例中,您尝试设置is_completed
。根据您的表格,它应为IsCompleted
。