Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a simple way to sum a result from UNION in MySql

Tags:

sql

mysql

union

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 
like image 957
Itay Moav -Malimovka Avatar asked Mar 05 '10 15:03

Itay Moav -Malimovka


People also ask

How do I count after a UNION in SQL?

Here is the query to count on the union query. mysql> select count(*) as UnionCount from -> ( -> select distinct UserId from union_Table1 -> union -> select distinct UserId from union_Table2 -> )tbl1; The following is the output displaying the count.

How do you sum up in MySQL?

You can use the SUM() function in a SELECT with JOIN clause to calculate the sum of values in a table based on a condition specified by the values in another table.

How do you sum results in SQL?

The SUM() function returns the total sum of a numeric column.

How do I get the sum of values in a row in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.


2 Answers

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 
like image 197
Jimmy Avatar answered Oct 07 '22 14:10

Jimmy


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.

like image 23
zerkms Avatar answered Oct 07 '22 14:10

zerkms