【发布时间】:2013-05-13 13:24:04
【问题描述】:
我在使用左连接 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"
当我运行查询时,即使我已经定义了余额,我也会收到错误“‘where 子句’中的未知列‘余额’”。
非常感谢任何帮助。谢谢!
【问题讨论】: