[英]Pull data from two DB2 tables, UNION ALL
I have two tables.. In output result I want to merge data from both. 我有两个表。在输出结果中,我想合并两个表中的数据。 So assume I have to use UNION statement.
因此,假设我必须使用UNION语句。 What I need in result set:
我在结果集中需要的是:
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
I need something like this: 我需要这样的东西:
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>
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))
Gives me: 给我:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.