Microsoft Access - Subtracting two columns from diff tables using sql statement

Asked By Joe Arcuch on 12-Mar-10 02:37 PM
Hi,
 Im using the following statement to substract or divide totals from two different tables (based on a response by John Spencer posted on Wednesday, March 05, 2026), and it works like a charm. However, I'm no SQL expert and I am having a hard time trying to figure out a second sort in the statement, so I can sort by Source (the way it works now) and also by Category which is the second parameter I wish to add. I've tried to integrate it in the current statement but I get an error at the JOIN.
Thx, I'm hoping this provides sufficient info...

SELECT A.Source, A.TotalExtCost, B.TotalExtCostSO, [TotalExtCost]-NZ([TotalExtCostSO],0) AS StockExtCost
FROM (SELECT Source, Sum(ExtCost) AS TotalExtCost FROM MRPSPartsSales_12months GROUP BY Source)  AS A LEFT JOIN (SELECT Source, Sum([ExtCost]) AS TotalExtCostSO FROM MRPSPartsSalesSO_12months GROUP BY Source)  AS B ON A.Source = B.Source
GROUP BY A.Source, A.TotalExtCost, B.TotalExtCostSO, [TotalExtCost]-NZ([TotalExtCostSO],0);



Jonathan VH replied to Joe Arcuch on 12-Mar-10 02:48 PM
If you mean group by Source and Category, you'd need to add that to the derived tables and then join on that, e.g.:

SELECT A.Source, A.Category, A.TotalExtCost, B.TotalExtCostSO, A.TotalExtCost-NZ(B.TotalExtCostSO,0) AS StockExtCost
FROM
(SELECT Source, Category, Sum(ExtCost) AS TotalExtCost
 FROM MRPSPartsSales_12months
 GROUP BY Source, Category)  AS A LEFT JOIN
(SELECT Source, Category, Sum(ExtCost) AS TotalExtCostSO
 FROM MRPSPartsSalesSO_12months
 GROUP BY Source, Category)  AS B ON A.Source = B.Source AND A.Category = B.Category
GROUP BY A.Source, A.Category, A.TotalExtCost, B.TotalExtCostSO, A.TotalExtCost-NZ(B.TotalExtCostSO,0);
Joe Arcuch replied to Jonathan VH on 12-Mar-10 02:55 PM
Thank you so much Jonathan,
That totally worked...