One approach using the join of the 2 tables deb
and cred
is as follows:
SELECT cred.accCategory, cred.ID, cred.Account, [deb].[Jan]+[cred].[Jan] AS tot_Jan
FROM cred INNER JOIN deb ON (cred.Account = deb.Account) AND (cred.ID = deb.ID) AND (cred.accCategory = deb.accCategory);
This screenshot shows how the query is constructed:
And here are the results (excuse the table formatting):
accCategory ID Account tot_Jan
1 1 Cash 5
1 2 Card 100
1 3 Savings 100
Be warned that the JOIN
is an equi-JOIN so it means the same number of records must exist in BOTH tables else you will find that credits where a debit does not exist will be dropped! So make sure that both input tables are consistent with the same key values (the 3 GROUP BY
fields in your earlier PIVOT query).
The alternative approach is the UNION
with a GROUP BY
to calculate the total from it. I will paste that shortly.
========== EDIT ============
You can build this up in stages. First I did SELECT * FROM cred UNION SELECT * FROM deb
and looked at in Design View.
Went back into the SQL view and made sure the UNION
query has brackets around it and SELECT sub.* FROM
before the brackets and AS SUB
after the brackets.
Then I modified the query to include the GROUP BY
and Sum(Jan)
bits. The final SQL is here and a screenshot follows.
SELECT sub.accCategory, sub.ID, sub.Account, Sum(sub.Jan) AS SumOfJan
FROM (SELECT * FROM cred UNION SELECT * FROM deb) AS sub
GROUP BY sub.accCategory, sub.ID, sub.Account;