简体   繁体   English

连接具有不同行和列的 2 个表

[英]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.我是 SQL 新手,在连接 2 个具有不同行和列的表时遇到问题。

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.在排序中,如果两个表之间的 Colx、Coly、Colz 具有完全相同的数据,我想总结结果表中的 ColData,否则我希望它保留在结果表中。

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.我正在使用 SQL Oracle 开发人员,但没有使用 PL/SQL 抱歉我的英语不好。

I think you want a full join :我想你想要一个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:您可以使用union allgroup by如下:

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!!干杯!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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