联接2个多对多关系表

时间:2019-03-31 20:35:17

标签: sql many-to-many access nested-queries

问题:

  

找到每个客户的订单总额和付款总额的净余额。

涉及4个表:OrderDetailsOrdersPaymentsCustomer

总额订单=数量订单*每个[在OrderDetails中]

总付款额=同一订单的不同付款额之和。

Customers通过Payments链接到OrdersCustomerNumberOrders通过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。

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

有人想救我吗?

2 个答案:

答案 0 :(得分:1)

在处理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

答案 1 :(得分:0)

SELECT c.customername, SUM(od.quantityordered*od.priceeach) as ordersum ,  SUM(p.amount) as paymentsum' 

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