phantom007 — 2008-12-09T07:41:21-05:00 — #1
I am confused how to do this.
I have two tables and each table has an "Amount" colum.
I need to sum up all the rows for column "Amount" in table A and sum up all the rows for column "Amount" in table B
and then subtract those two colums.
Here is what I am doing:
select tableA.city, sum(tableA.amount) - sum(tableB.amount)
group by tableB.city
Say: tableA Has the following data for column "Amount" and city=Hyderabad:
AND tableB Has the following data for column "Amount" and city=Hyderabad:
Now, my above query should do the following:
Sum all amounts for tableA, which comes to 126
Sum all amounts for tableB, which comes to 11
So 126 - 11 = 115
But I get the result 219
Any idea wots going on and how to fix it?
smadeira — 2008-12-09T07:53:40-05:00 — #2
You are getting Table A summed more than once because of your join. get rid of the subtraction of the sum()s and just print sum(a) and sum(b) and run the query to see how the joins are causing things to be double counted.
guido2004 — 2008-12-09T07:54:47-05:00 — #3
Joining these two tables on city, will give the following result:
This gives 252 - 33 = 219
phantom007 — 2008-12-09T07:57:15-05:00 — #4
Wots the solution then?
phantom007 — 2008-12-09T08:00:06-05:00 — #5
What I am doing is incorrect and there is a way?
Is it something not possible in one query?
r937 — 2008-12-09T08:02:29-05:00 — #6
obviously, the solution is: don't join
SELECT ( SELECT SUM(Amount) FROM tableA )
- ( SELECT SUM(Amount) FROM tableB ) AS difference
phantom007 — 2008-12-09T08:08:58-05:00 — #7
That worked, but can it also show the cities also incase there are more then one city?
r937 — 2008-12-09T08:12:28-05:00 — #8
i'm sorry, that solution works for the question you posted
if you change the question, then the solution has to change too -- obviously
please explain what you mean by "more than one city"
phantom007 — 2008-12-09T08:17:04-05:00 — #9
Sorry about that.
See, I might have multiple cities in both tableA and tableB.
I want to do a sum of all rows for column "Amount" for each city in tableA and then do a sum of all rows for column "Amount" for each city in tableA
then subtract the amount from both tables city wise.
EDIT: So that it looks like
City | Difference
City A | 55
City B | 22
City C | 543
City D | 212
r937 — 2008-12-09T08:41:30-05:00 — #10
, a.total - b.total AS difference
FROM ( SELECT city
, SUM(amount) AS total
BY city ) AS a
JOIN ( SELECT city
, SUM(amount) AS total
BY city ) AS b
ON b.city = a.city