Home Ask Login Register

Developers Planet

Your answer is one click away!

Tom February 2016

Sum col2 of two tables based on duplicate matching col1

I have 2 tables both structured as (id, views)

Table 1:
id  views
A   1
B   2
B   3
C   3
C   4
D   4

Table 2:
id  views
C   1
D   3
D   4
E   5
E   7
F   8

I'm looking to sum views of ids that are both in table 1 and 2 (id C and D) in this case so the output would be:

Table 3:
id  views
C   8
D   11


K S Nidhin February 2016

You could use the following query in your case :

select a.id,sum(a.views) from ( select * from table1 union table2 ) as a group by id;

kundam gouthami February 2016

select id,sum(views) from (select * from table1 union all select * from table2)a where a.id="C" or a.id="D" group by id;

Post Status

Asked in February 2016
Viewed 3,787 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life