【问题标题】:Sum a column from a table and subtract it to a summed column in another table对表中的一列求和,然后将其减去到另一个表中的求和列
【发布时间】:2015-07-17 17:41:31
【问题描述】:

我有两个表 TblInventory 和 TblWithdrawal。 TblInventory 有 productID 和 TblWithdrawal。

按 ProductID 分组,如何将 TblInventory 中的 Quantity 和 SUM TblWithdrawal 中的 Quantity 相加,然后将 SUBTRACT 相互求和,以便我可以得到每个 ProductID 的剩余数量或差异?

这是我想出的,但是当我运行查询时,它要求我输入一个错误的参数,因为我希望它自动遍历表并对每个 ProductID 进行操作。

SELECT TblInventory.ProductID,
       SUM(TblInventroy.Quantity) - SUM(TblWithdrawals.Quantity) As [Remaining]
FROM TblInventory
  LEFT JOIN TblWithdrawals ON TblInventory.ProductID = TblWithdrawals.ProductID 
WHERE TblInventory.ProductID = TblWithdrawals.ProductID
GROUP BY TblInventory.ProductID

谢谢。我真的需要解决这个问题!

【问题讨论】:

  • 它要求什么参数?可能是您拼错的 TblInventroy。
  • 不要将 WHERE 子句用于连接条件,将那个也移动到 ON 子句以获得真正的 LEFT JOIN 行为。 (就像现在一样,它作为常规内部连接执行......)

标签: sql ms-access-2010


【解决方案1】:

不要使用 WHERE 子句。并使用 INNER JOIN 而不是 LEFT JOIN

【讨论】:

    【解决方案2】:

    使用子查询,先写组sql,然后根据需要加入。看下面的sql。

    选择 invent.ProductID,invent.invQty-withdrawl.withdrQty 作为剩余
    FROM ( SELECT ProductID,SUM(Quantity) as invQty
    FROM TblInventory ) 作为发明
    左外连接
    ( SELECT ProductID,SUM(Quantity) as withdrQty
    FROM TblWithdrawals ) 作为提款
    ON invQty.ProductID=withdrawl.ProductID

    试试这个最好的祝福

    【讨论】:

    • 我觉得这个是对的。但是一旦我使用它,我就会在 JOIN 操作中遇到语法错误。这是我的代码:SELECT invent.ProductID, invent.invQty -raising.withdrawQty AS Remaining FROM (SELECT ProductID, SUM(Quantity) AS invQty FROM TblInventory) AS invent LEFT JOIN (SELECT ProductID, SUM(Quantity) AS withdrawQty FROM TblWithdrawals) AS提款invQty.ProductID =提款.ProductID
    • BOSS 应该是 LEFT OUTER JOIN。你写了 LEFT JOIN
    猜你喜欢
    • 2021-08-21
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多