简体   繁体   English

SQL Server 从多个表查询 SUM

[英]SQL Server query SUM from multiple tables

I came across an issue I cannot figure out unfortunately...不幸的是,我遇到了一个我无法弄清楚的问题......

I have 2 tables: Purchase Orders Lines AND Sales Orders Lines.我有 2 个表:采购订单行和销售订单行。 Now I need to pull info from a single PO AND also SUM of cases of a particular item (listed on that PO) FROM both Sales orders lines AND Purchase Orders lines.现在,我需要从销售订单行和采购订单行中提取单个采购订单的信息以及特定项目(在该采购订单上列出)的案例总和。 Like I am ordering 10 tables and I want to know that I already ordered 20 tables and I have sales orders for 25 tables.就像我订购了 10 张桌子,我想知道我已经订购了 20 张桌子并且我有 25 张桌子的销售订单。 Below is my query.以下是我的查询。

SELECT s.POLID, s.ItemID, s.CSordered,
SUM(sl.CSopen) AS CSopenSO, SUM(pl.CSopen) AS CSopenPO
FROM PurchaseOrdersLines s

LEFT JOIN SalesOrdersLines sl ON s.ItemID = sl.ItemID
LEFT JOIN PurchaseOrdersLines pl ON s.ItemID = pl.ItemID

WHERE s.POID = '" . $row['POID'] . "'
GROUP BY s.POLID, s.ItemID, s.CSordered

I am getting SUM of CSopenSO correct but not SUM CSopenPO (it is 50 times higher than it should be).我得到了 CSopenSO 的 SUM 正确但不是 SUM CSopenPO (它比它应该高 50 倍)。 If I switch LEFT JOIN bringing Purchase Orders (pl) first then Sales Orders (sl) - then I get correct SUM of CSopenPO but not SUM of CSopenSO.如果我先切换 LEFT JOIN 带来采购订单 (pl) 然后是销售订单 (sl) - 那么我得到正确的 CSopenPO 总和而不是 CSopenSO 的总和。 I do not understand how the order of LEFT JOIN affects the sums and how to avoid it.我不明白 LEFT JOIN 的顺序如何影响总和以及如何避免它。

Thank you for your help in advance!!!提前谢谢你的帮助!!! Hope if it was clear..希望如果清楚..

*** Suggested by Jarlh *** 由 Jarlh 推荐

SELECT s.POLID, s.ItemID, s.CSordered, (
SELECT SUM(CSopen) FROM SalesOrdersLines sl WHERE sl.ItemID = s.ItemID
) AS CSopenSO, SUM(pl.CSopen) AS CSopenPO 
FROM PurchaseOrdersLines s
LEFT JOIN PurchaseOrdersLines pl ON s.ItemID = pl.ItemID
WHERE s.POID = '" . $row['POID'] . "'
GROUP BY s.POLID, s.ItemID, s.CSordered

However I still want to understand why my original query above is not working the way I want it to work.但是,我仍然想了解为什么我上面的原始查询没有按照我希望的方式工作。 I would like to know what the error is.我想知道错误是什么。

Often, correlated subqueries are the most efficient method:通常,相关子查询是最有效的方法:

SELECT s.POLID, s.ItemID, s.CSordered,
       (SELECT SUM(sl.CSopen)
        FROM SalesOrdersLines sl 
        WHERE s.ItemID = sl.ItemID
       )  AS CSopenSO,
       (SELECT SUM(pl.CSopen)
        FROM PurchaseOrdersLines pl 
        WHERE s.ItemID = pl.ItemID
       ) AS CSopenPO 
FROM PurchaseOrdersLines s
WHERE s.POID = '" . $row['POID'] . "';

This assumes that the rows in s are not being combined.这假设s中的行没有被合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM