2

我正在尝试创建一个报告,该报告将显示具有未结帐户余额的客户,但是我似乎无法使用左联接使其工作。

我有 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");

谁能明白为什么这不起作用?

谢谢您的帮助!

4

1 回答 1

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
于 2013-04-07T14:40:36.780 回答