简体   繁体   English

SQL 链接三个表和 SUM

[英]SQL to link three tables and SUM

I have three tables, tblPresents, tblPresentsOrdered and tblPresentsDelivered.我有三个表,tblPresents、tblPresentsOrdered 和 tblPresentsDelivered。

What I want to do is sum up all the orders and deliveries for a given present ID, so I can tally up the total ordered and delivered and check for discrepancies.我想要做的是总结给定当前 ID 的所有订单和交付,所以我可以统计总订单和交付并检查差异。

So far I have the following:到目前为止,我有以下内容:

$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';

The first column (Ordered) is summing up correctly, but the deliveries is counting the delivery twice (there are two separate orders for that line).第一列 (Ordered) 总结正确,但交付计算了两次交付(该行有两个单独的订单)。

What am I doing wrong?我究竟做错了什么?

Because you can have multiple orders per delivery (and presumably multiple presents per order) you need to perform aggregation in derived tables before JOIN ing to avoid duplication in counted/summed values.因为每次交付可以有多个订单(并且可能每个订单有多个礼物),所以您需要在JOIN之前在派生表中执行聚合,以避免重复计数/求和值。 Note that using a mixture of LEFT JOIN and RIGHT JOIN in the same query can be a bit hard to read so I've rewritten the query using only LEFT JOIN s.请注意,在同一个查询中混合使用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