从两个DB2表中提取数据,UNION ALL

时间:2015-03-03 18:58:07

标签: sql db2

我有两个表..在输出结果中我想合并两者的数据。所以假设我必须使用UNION语句。我在结果集中需要什么:

  1. 仅来自TABLE1的第1行和第2行。
  2. 来自TABLE2的所有行,其中TABLE2 / COL4 = TABLE1 / COL1在#1中被选中,(这些是表2中的1和3)
  3. 在输出结果中,将COL2中的数据替换为TABLE2行的数据,其中包含来自TABLE1的COL2的数据
  4. TABLE1------------------------------------------
    COL1  COL2    COL3
    1     aaa1    eee1
    2     bbb1    fff1
    3     ccc1    ggg1
    4     ddd1    hhh1
    
    TABLE2------------------------------------------
    COL1  COL2    COL3    COL4
    1     aaa2    eee2    1
    2     bbb2    fff2    4
    3     ccc2    ggg2    1
    4     ddd2    hhh2    3
    
    RESULT I NEED-----------------------------------
    COL1  COL2    COL3
    1     aaa1    eee1
    2     bbb1    fff1
    1     aaa1    eee2
    3     aaa1    ggg2
    

    我需要这样的东西:

    SELECT#1 COL1, COL2, COL3 FROM TABLE1 WHERE COL1 IN ('1','2')
    UNION ALL
    SELECT#2 COL1, COL2 <AS SELECT#1.COL2>, COL3 FROM TABLE2 WHERE <COL4 IN SELECT#1.COL1>
    

1 个答案:

答案 0 :(得分:1)

select col1, col2, col3 from table1
WHERE COL1 IN (1,2)
union
select t2.col1,
       coalesce((select col2 from table1
                 WHERE COL1 IN (1,2)
                   AND COL1 = t2.col4),
                t2.col2),
       t2.col3
from table2 t2 join table1 t1 on t1.col1 = t2.col1 and col4 in
  (select col1 from table1 WHERE COL1 IN (1,2))

给我:

SQL>select * from table1
SQL&WHERE COL1 IN (1,2)
SQL&union
SQL&select t2.col1,
SQL&       coalesce((select col2 from table1
SQL&                 WHERE COL1 IN (1,2)
SQL&                   AND COL1 = t2.col4),
SQL&                t2.col2),
SQL&       t2.col3
SQL&from table2 t2 join table1 t1 on t1.col1 = t2.col1 and col4 in
SQL&  (select col1 from table1 WHERE COL1 IN (1,2))
SQL&;

       col1 col2   col3
       ==== ====   ====
          1 aaa1   eee1
          2 bbb1   fff1
          1 aaa1   eee2
          3 aaa1   ggg2

4 rows found