简体   繁体   中英

SQL inner join sum

I have 2 tables below. I want to join them and see the sums of c2 columns but the sum(table2.c2) result shows 18 instead of 9. How can I correct?

table1:

c1 c2  
a  6
a  0

table2

c1  c2
a   9
select table1.c1 ,sum(table1.c2), table2.c1, sum(table2.c2)
from table1
inner join table2
on table1.c1=table2.c1
GROUP BY table1.c1 ,table2.c1

result is as follows:

table1.c1   sum(table1.c2)  table2.c1   sum(table2.c2)
a           6               a           18

I expect like that:

table1.c1   sum(table1.c2)  table2.c1   sum(table2.c2)
a           6               a           9

You want to do the SUM before JOIN

select t1.c1, t1.sumc2, t2.c2, t2.sumc2
from (select c1, sum(c2) sumc2 from table1 group by c1) t1
join (select c1, sum(c2) sumc2 from table2 group by c1) t2 on t1.c1 = t2.c1

This is because you are inner joining on table1.c1 = table2.c1 and table1 has two rows, resulting in the single row in table2 being duplicated like this.

c1  t1.c2   t2.c2 
a     6       9 
a     0       9

The sums will therefore be 6 and 18. You can get around this by for example adding row numbers to your table or using inner selects or views to sum before you join the tables.

Try this

Select t.a, t.b, t1.a, t1.b
from (SElect a, sum(b) as b from tst group by a) t inner join tst1 t1 on (t.a = t1.a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM