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
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.
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.
The SUM() function returns the total sum of a numeric column.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With