用于数据整合的SQL查询

时间:2016-08-17 15:43:14

标签: sql oracle

这是我在这里的第一个问题..我有4个不同的表如下我希望合并数据如图所示使用SQL查询最好加入..我想知道是否有人可以帮助我这个!

数据表:

enter image description here

1 个答案:

答案 0 :(得分:0)

这是一种方法(使用WITH子句提供样本数据):

with table_a (col1, col2)
as
(select 'X', 10 from dual
  union all
 select 'Y', 30 from dual
  union all
 select 'Z', 50 from dual
)
, table_b (col1, col2)
as
(select 'M', 10 from dual
  union all
 select 'X', 20 from dual
  union all
 select 'Y', 30 from dual
)
, table_c (col1, col2)
as
(select 'N', 10 from dual
  union all
 select 'Y', 50 from dual
  union all
 select 'Z', 70 from dual
)
, table_d (col1, col2)
as
(select 'M', 10 from dual
  union all
 select 'N', 50 from dual
  union all
 select 'Z', 70 from dual
), 
 distinct_col1
as
(
SELECT col1
  FROM table_a
 UNION 
SELECT col1
  FROM table_b
UNION 
SELECT col1
  FROM table_c
UNION 
SELECT col1
  FROM table_d
)
SELECT d1.col1
     , t_a.col2 as a_col2
     , t_b.col2 as b_col2
     , t_c.col2 as c_col2
     , t_d.col2 as d_col2
  FROM distinct_col1 d1
       LEFT OUTER JOIN
       table_a t_a
          ON d1.col1 = t_a.col1
       LEFT OUTER JOIN
       table_b t_b
          ON d1.col1 = t_b.col1
       LEFT OUTER JOIN
       table_c t_c
          ON d1.col1 = t_c.col1
       LEFT OUTER JOIN
       table_d t_d
          ON d1.col1 = t_d.col1
ORDER BY d1.col1

使用物理表table_a,table_b,table_c和table_d,这只是:

with distinct_col1
as
(
SELECT col1
  FROM table_a
 UNION 
SELECT col1
  FROM table_b
UNION 
SELECT col1
  FROM table_c
UNION 
SELECT col1
  FROM table_d
)
SELECT d1.col1
     , t_a.col2 as a_col2
     , t_b.col2 as b_col2
     , t_c.col2 as c_col2
     , t_d.col2 as d_col2
  FROM distinct_col1 d1
       LEFT OUTER JOIN
       table_a t_a
          ON d1.col1 = t_a.col1
       LEFT OUTER JOIN
       table_b t_b
          ON d1.col1 = t_b.col1
       LEFT OUTER JOIN
       table_c t_c
          ON d1.col1 = t_c.col1
       LEFT OUTER JOIN
       table_d t_d
          ON d1.col1 = t_d.col1
ORDER BY d1.col1