我有一个像这样的表格设置
负债:
Id | CustomerId | liabilities
---------------------------
9 90 1000
...
付款:
Id | CustomerId | Payment
---------------------------
3 90 2500
4 91 1000
...
客户:
Id | balance
---------------------------
90 1500
91 1000
...
如您所见,客户的余额是其所有付款减去所有负债总和的总和。什么是更新余额的SQL查询?
答案 0 :(得分:2)
您可以使用带有UPDATE
操作的LEFT JOIN
语句对包含Payments
和Liabilities
聚合的派生表执行此操作:
UPDATE Customer AS c
LEFT JOIN (
SELECT CustomerId, SUM(Payment) AS TotalPayment
FROM Payments
GROUP BY CustomerId
) AS p ON c.Id = p.CustomerId
LEFT JOIN (
SELECT CustomerId, SUM(liabilities) AS TotalLiabilities
FROM Liabilities
GROUP BY CustomerId
) AS l ON c.Id = l.CustomerId
SET balance = COALESCE(TotalPayment, 0) - COALESCE(TotalLiabilities, 0)
或者,您可以在UPDATE
语句中使用相关子查询:
UPDATE Customer AS c
SET balance = COALESCE((SELECT SUM(Payment)
FROM Payments
WHERE CustomerId = c.Id) , 0)
-
COALESCE((SELECT SUM(liabilities)
FROM Liabilities
WHERE CustomerId = c.Id) , 0)