简体   繁体   中英

Joining two table with rows and column and sum them

I have a table that looks like

ColA  ColB  ColC ColD  ColE  ColF
 A    B      C    D     E      F

I want to join each rows of this table to another table

Column1  values
 A          1 
 A          2
 B          1 
 B          2

The resulting output will be sum of the column values from table 2. For example, First row of table 1 has A,B that are present in table 2 and their combined sum is 6.

ColA  ColB  ColC ColD  ColE  ColF    sum
 A    B      C    D     E      F      6

Any ideas how to do that in MYSQL?

You can do this with a subquery:

select t.*,
       (select sum(t2.value)
        from t2
        where t2.column1 in (t.cola, t.colb, t.colc, t.cold, t.cole, t.colf)
       ) as total
from t;

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