连接 2 个多对多关系表

Joining 2 Many-To-Many Relationship Tables

问题:

Find the net balance of the total order amount and total payments for each customer.

涉及4张表:OrderDetailsOrdersPaymentsCustomer

订单总金额=订单数量*单价[in OrderDetails]

支付总额=同一个订单不同支付金额之和。

Customers 链接到 PaymentsOrders 链接到 CustomerNumberOrders 链接到 OrderDetails OrderNumber

我尝试使用 INNER JOIN 函数连接 4 个表。

SELECT
    c.customername, 
    SUM(od.quantityordered * od.priceeach) - SUM(p.amount) AS Net_Balance
FROM 
    (
        (
            orderdetails od 
            INNER JOIN orders o ON od.ordernumber = o.ordernumber
        )  
        INNER JOIN customers c ON o.customernumber = c.customernumber
    )      
    INNER JOIN payments p ON c.customernumber = p.customernumber
GROUP BY c.customername;

几乎每个客户的预期结果都应该是 0。

然而,我得到的是总金额订单和总付款乘以一些常数。具体来说,显示的总付款乘以每个订单的付款次数。

有人有什么办法可以挽救我的生命吗?

这是处理 N-M 关系时的典型问题。要解决它,一种解决方案是将聚合移动到子查询:

SELECT c.customername, o.amt - p.amt AS Net_Balance
FROM customers c 
INNER JOIN (
    SELECT ord.customernumber, SUM(det.quantityordered * det.priceeach) as amt
    FROM orders ord
    INNER JOIN orderdetails det ON ord.ordernumber = det.ordernumber
    GROUP BY ord.customernumber
) o ON o.customernumber = c.customernumber
INNER JOIN (
    SELECT customernumber, SUM(amount) as amt
    FROM payments
    GROUP BY customernumber
) p ON p.customernumber = c.customernumber
SELECT c.customername, SUM(od.quantityordered*od.priceeach) as ordersum ,  SUM(p.amount) as paymentsum' 

这两列的结果是什么?
这是你想要的吗?