tags:

views:

63

answers:

3

I have a union of three tables (t1,t2,t3). Each rerun exactly the same number of records, first column is id, second amount:

1  10
2  20
3  20

1  30
2  30
3  10

1  20
2  40
3  50

Is there a simple in sql way to sum it up to only get:

1   60
2   80
3   80
+1  A: 
SELECT id, SUM(amount) FROM
(
    SELECT id, SUM(amount) AS `amount` FROM t1 GROUP BY id
  UNION ALL
    SELECT id, SUM(amount) AS `amount` FROM t2 GROUP BY id
) `x`
GROUP BY `id`

I groupped each table and unioned because i think it might be faster, but you should try both solutions.

zerkms
+1  A: 
select id, sum(amount) from (
    select id,amount from table_1 union all
    select id,amount from table_2 union all
    select id,amount from table_3
) x group by id
Jimmy
+1  A: 

Subquery:

SELECT id, SUM(amount)
FROM ( SELECT * FROM t1
       UNION ALL SELECT * FROM t2
       UNION ALL SELECT * FROM t3
     )
GROUP BY id
adharris
Note: you shouldn't use select * in this case.
David Oneill
Note 2: I bet mysql will ask you to assign alias to subquery
zerkms
@David: For sure, my bad. Probably doesn't matter if id and amount are the only two columns, but what are the chances of that?@zerkms: Also true.
adharris
@adharris: exactly. And even if there are only id and amount for now, there's no sense in shooting yourself in the foot when you add a third column in 6 months... :)
David Oneill