我正在尝试创建一个报告,该报告将显示具有未结帐户余额的客户,但我似乎无法使用左联接使其工作。
我有3个表 - 客户,购买和付款,我正在尝试显示总购买成本低于付款的客户大于0。
到目前为止,我有以下查询:
mysqli_query("SELECT customers.name as name, SUM(purchases.cost) as cost, SUM(payments.paymentamount) as payments FROM customers
LEFT JOIN purchases ON purchases.customerid = customers.id
LEFT JOIN payments ON payments.customerid = customers.id
WHERE (cost - payments) > 0
GROUP BY customers.id");
有人能看出为什么这不起作用吗?
感谢您的帮助!
答案 0 :(得分:2)
您需要为每个customerID
计算子查询的每个总计,以避免错误的结果。
SELECT a.*,
COALESCE(b.totalPurchase , 0) - COALESCE(c.totalPayment , 0) AS Balance
FROM customers a
LEFT JOIN
(
SELECT customerid, SUM(cost) totalPurchase
FROM purchases
GROUP BY customerid
) b ON a.ID = b.customerID
LEFT JOIN
(
SELECT customerid, SUM(paymentamount) totalPayment
FROM payments
GROUP BY customerid
) c ON a.ID = c.customerID
WHERE COALESCE(b.totalPurchase , 0) - COALESCE(c.totalPayment , 0) > 0