我有来自不同表格的以下数据集
Table1
-------
EMPID DEPID C1 C2 SUM
---------------------------
100 200 2 3 111
100 200 4 4 222
Table2
-------
EMPID DEPID C1 C2 SUM
---------------------------
100 200 4 4 333
100 200 5 6 444
结果我正在寻找---
Table1
-------
EMPID DEPID T1.C1 T1.C2 T2.C1 T2.C2 T1.SUM T2.SUM
--------------------------------------------------------------
100 200 2 3 NULL NULL 111 NULL
100 200 4 4 4 4 222 333
100 200 NULL NULL 5 6 NULL 444
任何帮助都很受欢迎。我使用了Full Outer Join但是无法实现这一点。
答案 0 :(得分:3)
您希望INNER JOIN
(emp_id, dep_id)
FULL OUTER JOIN
(c1, c2)
FULL OUTER JOIN
。我想你将无法在一个步骤中编写此连接条件。我提出了两步查询(SQL> WITH t1 AS (
2 SELECT 100 emp_id, 200 dep_id, 2 c1, 3 c2, 111 sum FROM dual UNION ALL
3 SELECT 100 emp_id, 200 dep_id, 4 c1, 4 c2, 222 sum FROM dual
4 ), t2 AS (
5 SELECT 100 emp_id, 200 dep_id, 4 c1, 4 c2, 333 sum FROM dual UNION ALL
6 SELECT 100 emp_id, 200 dep_id, 5 c1, 6 c2, 444 sum FROM dual UNION ALL
7 SELECT 100 emp_id, 300 dep_id, 7 c1, 8 c2, 555 sum FROM dual
8 )
9 SELECT COALESCE(t1.emp_id, t2.emp_id) emp_id,
10 COALESCE(t1.dep_id, t2.dep_id) dep_id,
11 t1.c1, t1.c2, t2.c1, t2.c2, t1.sum, t2.sum
12 FROM t1
13 FULL OUTER JOIN t2
14 ON t1.emp_id = t2.emp_id
15 AND t1.dep_id = t2.dep_id
16 AND t1.c1 = t2.c1
17 AND t1.c2 = t2.c2
18 WHERE (COALESCE(t1.emp_id, t2.emp_id), COALESCE(t1.dep_id, t2.dep_id))
19 IN (SELECT t1.emp_id, t1.dep_id
20 FROM t1
21 JOIN t2 ON t1.emp_id = t2.emp_id
22 AND t1.dep_id = t2.dep_id)
23 ORDER BY t1.c1;
EMP_ID DEP_ID C1 C2 C1 C2 SUM SUM
---------- ---------- ---------- ---------- ---------- ---------- ---- ----
100 200 2 3 111
100 200 4 4 4 4 222 333
100 200 5 6 444
后跟过滤子查询)。
T2
请注意,我在您的示例的INNER JOIN
中添加了一行,以演示{{1}}。