【问题标题】:How to merge two tables together and keep all the records that match and do not match-Oracle SQL如何将两张表合并在一起,并保留所有匹配和不匹配的记录-Oracle SQL
【发布时间】:2021-11-07 06:14:03
【问题描述】:

我有两个表,我正在尝试将它们合并在一起以创建它们的联合输出。

这是我的表格的结构:

表 1:

date type_s calls declines
09-SEP-21 insurance 500 600
09-SEP-21 roadside 66 60
09-SEP-21 AAA 34 700
09-SEP-21 retail 1 650

表 2:

date type_s cnt
09-SEP-21 insurance 5
09-SEP-21 AAA 3
09-SEP-21 retail 79

如何让我的输出变成这样:

date type_s calls declines cnt
09-SEP-21 insurance 500 600 5
09-SEP-21 roadside 66 60 0
09-SEP-21 AAA 34 700 3
09-SEP-21 retail 1 650 79

请注意,在表 2 中,路边不存在,因为没有该类型的数据。我正在尝试将它们合并在一起以保留所有记录,即使表 1 中的列 'type_s' 中的数据在表 2 中不存在。在这种情况下,只需将 0 作为该类型的 cnt。

到目前为止,这是我的代码:

with t2 as
(select DATE_TIME , type_s, calls, declines
 from table_1
 ),
CD as
(
SELECT 
DATE_TIME, type_s, CNT
FROM table2
),
DD AS(
SELECT TO_DATE(current_date - 1) AS chart_date,
type_s,
calls,
declines
FROM t2),
GG As
(
SELECT 
DD.chart_date ,
DD.type_s,
DD.calls,
DD.declines,
CD.CNT
FROM CD,DD
WHERE CD.type_s= DD.type_s)
select CHART_DATE,type_s,calls,declines,cnt
from GG;

我的代码运行良好,但它没有给我想要的输出(见下文)。它不包括表 1 中的路边行。

date type_s calls declines cnt
09-SEP-21 insurance 500 600 5
09-SEP-21 AAA 34 700 3
09-SEP-21 retail 1 650 79

关于如何修复我的代码以创建我想要的输出的任何想法或建议?任何帮助将不胜感激。

【问题讨论】:

    标签: sql oracle join oracle11g


    【解决方案1】:

    看起来像一个带有NVL 函数的外连接。第 1 - 12 行中的示例数据,查询从第 13 行开始。

    SQL> with
      2  table1 (datum, type_s, calls, declines) as
      3    (select date '2021-09-09', 'insurance', 500, 600 from dual union all
      4     select date '2021-09-09', 'roadside' ,  66,  60 from dual union all
      5     select date '2021-09-09', 'AAA'      ,  34, 700 from dual union all
      6     select date '2021-09-09', 'retail'   ,   1, 650 from dual
      7    ),
      8  table2 (datum, type_s, cnt) as
      9    (select date '2021-09-09', 'insurance',  5 from dual union all
     10     select date '2021-09-09', 'AAA'      ,  3 from dual union all
     11     select date '2021-09-09', 'retail'   , 79 from dual
     12    )
     13  select a.datum, a.type_s, a.calls, a.declines, nvl(b.cnt, 0) cnt
     14  from table1 a left join table2 b on a.datum  = b.datum
     15                                  and a.type_s = b.type_s
     16    /
    
    DATUM      TYPE_S         CALLS   DECLINES        CNT
    ---------- --------- ---------- ---------- ----------
    2021-09-09 insurance        500        600          5
    2021-09-09 AAA               34        700          3
    2021-09-09 retail             1        650         79
    2021-09-09 roadside          66         60          0
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 2019-10-03
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 2016-10-11
      相关资源
      最近更新 更多