a simple way to sum a result from UNION in MySql

Itay Moav -Malimovka picture Itay Moav -Malimovka · Mar 5, 2010 · Viewed 88.6k times · Source

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

Answer

Jimmy picture Jimmy · Mar 5, 2010
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