你想要一個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
。
什麼版本的oracle? – Taryn 2013-04-04 13:08:34
加入哪些列? 't1.c1 = t2.c1'? 't1.c2 = t2.c2'?兩個都?或者't1.c1 = t2.c2'? 't2.c1 = t1.c2'?或者這兩個? – 2013-04-04 13:12:28
連接條件是T1.EMP_ID = T2.EMP_ID和T1.DEP_ID = T2.DEP_id和T1.C1 = T2.C1和T1.C2 = T2.C2 .. SO我正在檢查上述四個條件,如果C1和C2匹配我打印來自兩個表的SUM,否則相應的庫侖將爲NULL。 – 2013-04-04 13:38:27