我在使用左连接 SQL 查询时遇到问题,但不明白为什么它不起作用。我有 3 个表:客户、采购和付款,我正在尝试选择总采购成本低于总付款的客户(即他们的余额大于 0)。
到目前为止,我有以下内容:
表:
Customers
id | Name
Purchases
id | customerid | cost
Payments
id | customerid | paymentamount
SQL查询:
SELECT a.*,
COALESCE(b.totalCost , 0) as totalCost,
COALESCE(c.totalPayments , 0) as totalPayments,
COALESCE(b.totalCost , 0) - COALESCE(c.totalPayments , 0) AS Balance
FROM customers a
LEFT JOIN (SELECT customerid, SUM(cost) AS totalCost FROM purchases GROUP BY customer) b ON a.id = b.customerid
LEFT JOIN (SELECT customerid, SUM(paymentamount) AS totalPayments FROM payments GROUP BY customerid) c ON a.id = c.customerid
WHERE Balance > 0"
当我运行查询时,即使我已经定义了 Balance,我也会在“where 子句”中收到错误“Unknown column 'Balance'”。
任何帮助深表感谢。谢谢!