联盟合并不同的列

时间:2016-08-02 11:18:17

标签: sql oracle merge union

我有两张桌子:

Table1

DATAID|   NAME   | FACTOR

 1    |   Ann    |   1
 2    |   Kate   |   1
 3    |   Piter  |   1 

Table2

DATAID|   NAME   | FACTOR

 1    |   John    |   2
 6    |   Arse    |   2
 3    |   Garry   |   2 

我希望UNION这些表格并获得此结果:

DATAID|   NAME    | FACTOR

 1    |   Ann     |   1,2
 2    |   Kate    |   1
 3    |   Piter   |   1,2
 6    |   Arse    |   2 

因此,如果有2行具有相同的数据ID,我希望获得“NAME' Table1中的列和某种聚合因子,例如' 1,2'或3

2 个答案:

答案 0 :(得分:1)

一种方法使用listagg()

select dataid, name,
       listagg(factor, ',') within group (order by factor) as factors
from ((select dataid, name, factor from table1 t1
      ) union all
      (select dataid, name, factor from table2 t2
      )
     ) t
group by dataid, name;

注意:我注意到给定ID的名称​​不相同。您可以使用聚合函数选择一个。

或者,如果每个表中只有一行,则可以使用full outer join

select coalesce(t1.dataid, t2.dataid) as dataid,
       coalesce(t1.name, t2.name) as name,
       trim(leading ',' from coalesce(',' || t1.factor, ',') || coalesce(',' || t2.factor, '') as factors
from t1 full outer join
     t2
     on t1.dataid = t2.dataid;

答案 1 :(得分:0)

这样的事情应该有效。在您的实际情况中,您不需要前两个CTE(我在测试中添加的WITH子句中的子查询)。

with 
     table1 ( dataid, name, factor ) as (
       select 1, 'Ann'  , 1 from dual union all
       select 2, 'Kate' , 1 from dual union all
       select 3, 'Piter', 1 from dual
     ),
     table2 ( dataid, name, factor ) as (
       select 1, 'John' , 2 from dual union all
       select 6, 'Arse' , 2 from dual union all
       select 3, 'Garry', 2 from dual
     ),
     u ( dataid, name, factor, source ) as (
       select dataid, name, factor, 1 from table1
       union all
       select dataid, name, factor, 2 from table2
     ),
     z ( dataid, name, factor ) as (
       select dataid, first_value(name) over (partition by dataid order by source), 
              factor
       from   u
     )
select dataid, name,
       listagg(factor, ',') within group (order by factor) as factor
from   z
group by dataid, name
order by dataid
;

输出:

 DATAID NAME  FACTOR
------- ----- ---------
      1 Ann   1,2
      2 Kate  1
      3 Piter 1,2
      6 Arse  2

4 rows selected.