简体   繁体   中英

Join 2 tables with different row and column

I'm new to SQL and having problem with joining 2 tables with different rows and columns.

Table 1 (has more than 4 columns)
Colx      Coly      Colz      ColData      Col...
x1        y1        z1        a            1
x2        y2        z2        b            2
x3        y3        z3        c            3
x4        y4        z4        d            4
x5        y5        z5        e            5


Table 2 (has 4 columns)
Colx      Coly      Colz      ColData
x1        y2        z1        f
x2        y2        z2        g
x3        y4        z4        h
x4        y4        z4        i

The result that I want

Colx      Coly      Colz      ColData      Col...
x1        y1        z1        a            1
x2        y2        z2        b+g          2
x3        y3        z3        c            3
x4        y4        z4        d+i          4
x5        y5        z5        e            5
x1        y2        z1        f            null
x3        y4        z4        h            null

In sort, I want to sum up ColData in result table if Colx, Coly, Colz between 2 tables have exactly same data, if not I want it remain in result table.

I have tried may way include left, right join, full join, union, full union but the result is not what I want. But it always end up like this.

Colx      Coly      Colz      ColData      Col...
x2        y2        z2        b+e          2
x4        y4        z4        d+i          4

I'm using SQL Oracle developer but not using PL/SQL Sorry for my bad English.

I think you want a full join :

select colx, coly, colz,
       coalesce(t1.colData, 0) + coalesce(t2.colData, 0),
       t1.colzzz
from t1 full join
     t2
     using (colx, coly, colz);

You can use union all and group by as following:

Select colx, coly, colz, 
       Listagg(coldata, '+') within group (order by coldata) as coldata, 
       -- if coldata is number then use sum(coldata)
      Col...
From
  (Select colx, coly, colz, coldata, col...
     From table1
   Union all
   Select colz, coly, colz, coldata, null as "col..."
     From table2)
Group by colx, coly, colz

Cheers!!

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