从两个 DB2 表中提取数据,UNION ALL
Pull data from two DB2 tables, UNION ALL
我有两个表。在输出结果中我想合并两个表的数据。所以假设我必须使用 UNION 语句。我需要的结果集:
- 仅来自 TABLE1 的第 1 行和第 2 行。
- TABLE2 中的所有行,其中 TABLE2/COL4 = TABLE1/COL1 在 #1 中选择,(这些是 TABLE2 中的 1 和 3)
- 在输出结果中,用来自 TABLE1 的 COL2 的数据替换 TABLE2 行的 COL2 中的数据
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>
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
我有两个表。在输出结果中我想合并两个表的数据。所以假设我必须使用 UNION 语句。我需要的结果集:
- 仅来自 TABLE1 的第 1 行和第 2 行。
- TABLE2 中的所有行,其中 TABLE2/COL4 = TABLE1/COL1 在 #1 中选择,(这些是 TABLE2 中的 1 和 3)
- 在输出结果中,用来自 TABLE1 的 COL2 的数据替换 TABLE2 行的 COL2 中的数据
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>
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