簡體   English   中英

SQL 鏈接三個表和 SUM

[英]SQL to link three tables and SUM

我有三個表,tblPresents、tblPresentsOrdered 和 tblPresentsDelivered。

我想要做的是總結給定當前 ID 的所有訂單和交付,所以我可以統計總訂單和交付並檢查差異。

到目前為止,我有以下內容:

$sql ='SELECT prsName, SUM(ordQuantity) AS qtyOrdered,
SUM(delQuantity) AS qtyDelivered
FROM tblPresentOrders
LEFT JOIN tblPresentDeliveries
ON tblPresentDeliveries.delPresent = tblPresentOrders.ordPresent
RIGHT JOIN tblPresents ON tblPresents.prsID = tblPresentOrders.ordPresent
GROUP BY prsName';

第一列 (Ordered) 總結正確,但交付計算了兩次交付(該行有兩個單獨的訂單)。

我究竟做錯了什么?

因為每次交付可以有多個訂單(並且可能每個訂單有多個禮物),所以您需要在JOIN之前在派生表中執行聚合,以避免重復計數/求和值。 請注意,在同一個查詢中混合使用LEFT JOINRIGHT JOIN可能有點難以閱讀,因此我只使用LEFT JOIN重寫了查詢。

SELECT p.prsName, o.qtyOrdered, d.qtyDelivered
FROM tblPresents p
LEFT JOIN (SELECT ordPresent, SUM(ordQuantity) AS qtyOrdered
           FROM tblPresentOrders
           GROUP BY ordPresent) o ON o.ordPresent = p.prsID
LEFT JOIN (SELECT delPresent, SUM(delQuantity) AS qtyDelivered
           FROM tblPresentDeliveries
           GROUP BY delPresent) d ON d.delPresent = p.prsID

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM