Let say I have two table with 2 columns :
Table A :
Job | Cost |
---|---|
1 | 100 |
1 | 200 |
2 | 100 |
2 | 150 |
2 | 50 |
And Table B :
Job | Sell |
---|---|
1 | 100 |
1 | 100 |
1 | 200 |
2 | 100 |
2 | 100 |
And I want result query by joining these two tables, as below :
Job | Cost | Sell |
---|---|---|
1 | 300 | 400 |
2 | 300 | 200 |
I try the query as below and the result not as expected :
SELECT A.Job,
SUM(A.Cost) AS NCOST,
SUM(B.Sell) AS NSELL
FROM TableA A
JOIN TableB B ON A.Job= B.Job
GROUP BY A.Job;
Can anyone help me to correct my query ?
3
Answers
You need to calculate totals separately, then join the two datasets :
Demo here
You need to aggregate each table first, so that each Job value appears only once, and then join the two aggregated datasets.
At the moment, as Job appears multiple times in the first table if you just join the two tables you’ll get duplicated rows
Instead of a join use
UNION ALL
and then aggregate: