Oracle SQL-如何将两个表一对一联接?

时间:2018-09-16 14:30:13

标签: sql oracle

我正在寻找一个完整的外部联接,以获得以下结果。主要是我将表1加入表2。

但是在表1中,在列A中具有0但在键1列中具有相同的可用值(表1中的ABC100键1值)的任何东西,仅使用该记录(表1中的记录1),并忽略0条记录(表1中的记录2)

当加入表2(特别是针对ABC100的表)时,我期望在预期的表结果中看到输出行1和2。

有什么帮助或想法吗?

示例:

表1

| Key 1    | Column A | 
| ABC100   | 100      |  
| ABC100   | 0        |  
| ABC300   | 200      | 
| ABC400   | 300      | 

表2

| Key 2    | Column C | 
| ABC100   | 100      |
| ABC200   | 50       |   
| ABC300   | 200      |  

预期结果:

| Key 1    | Column A | Key 2     | Column B | NVL(A,0) - NVL(B,0)
| ABC100   | 100      |  ABC100   | 100      | 0 
| ABC100   | NULL     |  NULL     | NULL     | NULL
| NULL     | NULL     |  ABC200   | 50       | -50
| ABC300   | 200      |  ABC300   | 200      | 0
| ABC400   | 300      |  NULL     | NULL     | 300

2 个答案:

答案 0 :(得分:1)

您的结果集表明您想要这样的东西:

SELECT t1.key1,
       (CASE WHEN t1.a <> 0 THEN t1.a END) as a,
       (CASE WHEN t1.a <> 0 THEN t2.key2 END) as key2,
       (CASE WHEN t1.a <> 0 THEN t2.c END) as ,
       (CASE WHEN t1.a <> 0 THEN COALESCE(t1.A, 0) - COALESCE(t2.B, 0) END) as diff
FROM t1 FULL JOIN
     t2
     ON t1.Key1 = t2.Key2;

您的描述表明您想要

SELECT t1.key1, t1.a, t2.key2, t2.c,
       COALESCE(t1.A, 0) - COALESCE(t2.B, 0) as diff
FROM (SELECT t1.*
      FROM 
      WHERE t1.A <> 0 OR
            NOT EXISTS (SELECT 1 FROM t1 tt1 WHERE tt1.key1 = t1.key1 AND tt1.key1 <> 0)
     ) t1 FULL JOIN
     t2
     ON t1.Key1 = t2.Key2;

答案 1 :(得分:0)

您可以使用:

SELECT t1.*, t2.*, NVL(t1.A,0) - NVL(t2.B,0)
FROM tab1 t1
FULL JOIN tab2 t2
  ON t1.Key1=t2.Key2