I have 2 tables AP and INV where both have the columns [PROJECT] and [Value].
I want a query to return something like this :
PROJECT | SUM_AP | SUM_INV
I came up with the code below but it's returning the wrong results ( sum is wrong ).
SELECT AP.[PROJECT],
SUM(AP.Value) AS SUM_AP,
SUM(INV.Value) AS SUM_INV
FROM AP INNER JOIN INV ON (AP.[PROJECT] =INV.[PROJECT])
WHERE AP.[PROJECT] = 'XXXXX'
GROUP BY AP.[PROJECT]
how about this query :
here is the link to the ERD: http://dl.dropbox.com/u/18794525/AUG%207%20DUMP%20STAN.png
Try:
If PROJECT is the parent table, you should select FROM the project table, and do a left outer join on the two child tables:
You could separate the two sum calculations. One way I can think of is to move the inventory calculation to a subquery, like:
Because the
SummedInv
subquery is grouped onproject
, it's safe to group onSummedInv.SUM_INV
in the outer query as well.The results from your query are wrong because the values you are trying to summarize are being grouped, which causes duplicate values to be included in the
SUM
.You could solve it with a couple of sub-selects:
If you have
N
rows in AP with a given project ID, andM
rows in INV with that ID, then the join between the two tables on the project ID will have a total ofN*M
rows for that project, because the same row in AP will be repeated for every row in INV that has that project ID, and vice versa. Hence why your counts are most likely off (because it's counting the same row in a given table multiple times due to repetition from the join).Instead, you might want to try doing a join between the results of two subqueries, one which groups the first table by project ID and does that its sum, and the second which groups the other table by project ID and does that sum - then joining once you only have 1 row with sum for each project ID.