简体   繁体   中英

Sum a column from a table and subtract it to a summed column in another table

I have two tables TblInventory and TblWithdrawal. TblInventory has productID as well as TblWithdrawal.

Grouping by ProductID, how do I SUM the Quantity in TblInventory and SUM the Quantity in TblWithdrawal and then SUBTRACT it to one another so I can get the remaining or difference in Quantity of each ProductID?

This is what I came up with, but when I run the query, it asks me to input a parameter which is wrong because I want it to automatically go through the table and do the operations on each 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

Thank you. I really need to solve this!

Don't user WHERE clause. And use INNER JOIN instead of LEFT JOIN

Use Sub queries,First write group sqls then join it as you want. Look following sql.

SELECT invent.ProductID, invent.invQty- withdrawl.withdrQty as Remaining
FROM ( SELECT ProductID,SUM(Quantity) as invQty
FROM TblInventory ) as invent
LEFT OUTER JOIN
( SELECT ProductID,SUM(Quantity) as withdrQty
FROM TblWithdrawals ) as withdrawl
ON invQty.ProductID=withdrawl.ProductID

Try This Best wishes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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