I was reading this post from StackOverFlow
to adjust query to calculate stock from 3 tables. I have 3 tables tblItems
, tblPurchase
and tblSales
. tblItems
contains items information like below.
ItemCode Description ItemClass ItemCategory ReorderLevel Unit Stop IT000001 Tonner 226A Tonner IT Accessories 10 Pc(s) No IT000002 Keyborad (A4Tech, Slim Key) Keyboard IT Accessories 10 Pc(s) No IT000003 Mouse (Wireless) Mouse IT Accessories 10 Pc(s) No SI000001 A4 Size Paper Paper Office Stationary 10 Pc(s) No SI000002 Pen (Black) Pen Office Stationary 10 Pc(s) No SI000003 Pen (Blue) Pen Office Stationary 10 Pc(s) No
Screenshots of my tables
tblItems:
tblPurchase:
tblSales:
And my expected result like below
In query result items details will come from tblItems
. Sum purchase quantity per item and sum sales quantity per item then minus SalesQuantity
from PurchaseQuantity
to see stock.
Here is my query which gives me following warning.
SELECT DISTINCTROW tblItems.ItemCode, TblItems.Description, TblItems.ItemClass, TblItems.ItemCategory, TblPurchaseAgg.[pQuantity], TblSalesAggs.[sQuantity] FROM (TblItems LEFT JOIN (SELECT TblItems.ItemCode AS ItemCode, Sum(TblPurchase.Quantity) AS pQuantity FROM TblItems LEFT JOIN TblPurchase ON TblItems.ItemCode = TblPurchase.ItemCode GROUP BY TblItems.ItemCode) AS TblPurchaseAgg ON TblItems.ItemCode = TblPurchaseAgg.ItemCode) LEFT JOIN (SELECT TblItems.ItemCode AS ItemCode, Sum(tblSales.Quantity) AS sQuantity FROM TblItems LEFT JOIN tblSales ON TblItems.ItemCode = tblSales.ItemCode GROUP BY TblItems.ItemCode) AS TblSalesAggs ON TblItems.ItemCode = TblSalesAggs.ItemCode GROUP BY TblItems.ItemCode, TblItems.Description, TblItems.ItemClass, TblItems.ItemCategory;
Seeking help to resolve the warning and get my expected output. Any help is greatly appreciated. Thanks in advance.
Advertisement
Answer
You don’t need the outer/first group. Since your item table will [probably]
will never have duplicate items the records returned will always be unique.
the both left joins you are using is grouping by itemCode
so they also will only return one record per item. so grouping overall is not required.
this could work for you:
SELECT tblItems.ItemCode, TblItems.Description, TblItems.ItemClass, TblItems.ItemCategory, TblPurchaseAgg.pQuantity, TblSalesAggs.sQuantity, (TblPurchaseAgg.pQuantity - TblSalesAggs.sQuantity) as stock, TblItems.unit FROM (TblItems LEFT JOIN ( SELECT TblPurchase.ItemCode AS ItemCode, Sum(TblPurchase.Quantity) AS pQuantity FROM TblPurchase GROUP BY TblPurchase.ItemCode ) AS TblPurchaseAgg ON TblItems.ItemCode = TblPurchaseAgg.ItemCode) LEFT JOIN ( SELECT tblSales.ItemCode AS ItemCode, Sum(tblSales.Quantity) AS sQuantity FROM tblSales GROUP BY tblSales.ItemCode ) AS TblSalesAggs ON TblItems.ItemCode = TblSalesAggs.ItemCode