Question

I have 2 tables with partially same columns which I want to combine in one query:

table 1
|id    |user  |amount |date
|1     |4     |1000   |2014-01-01 01:00:00
|2     |1     |2000   |2014-01-01 01:00:00
|3     |2     |1500   |2014-01-01 01:00:00

table 2
|id    |user  |amount |date                |flag
|1     |4     |1000   |2014-01-01 01:00:00 |0
|2     |3     |2000   |2014-01-01 01:00:00 |1
|3     |5     |1500   |2014-01-01 01:00:00 |2

I want to list the contents the two tables have in common but I want to add the amount column. So if a user is in table 1 and 2, even multiple times in both it should just list him 1 time in the result but the amount should add up.

So a result should be the following:

result
|user  |amount |date                
|4     |2000   |2014-01-01 01:00:00  <- note the 2000 here (1000+1000)
|1     |2000   |2014-01-01 01:00:00 
|2     |1500   |2014-01-01 01:00:00 
|3     |2000   |2014-01-01 01:00:00 
|5     |1500   |2014-01-01 01:00:00 

I thought of a query like

SELECT user, amount, date FROM (
    (SELECT user, amount, date FROM table1)
UNION
    (SELECT user, amount, date FROM table2)
) t1

but this doesn't add up the amount value and entries get listed multiple times. If I use GROUP BY, it only lists entries 1 time but entries get cut meaning amount also doesn't sum up. Using SUM, it adds just all entries and displays 1 entry but I need to have all entries 1 time with the amount column sum up.

Was it helpful?

Solution

Try this using aggregate functions you should use group by without group by you will get only one row

SELECT t1.user, SUM(t1.amount), t1.date FROM (
    (SELECT user, amount, date FROM table1)
UNION ALL
    (SELECT user, amount, date FROM table2)
) t1

GROUP BY t1.user

GROUP BY (Aggregate) Functions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top