Oracle SQL - 连接两个表 + 显示不匹配的结果

Oracle SQL - join two tables + show unmatched results

我有两个表:

POSITION_TABLE

Account Security Pos_Quantity
1 A 100
2 B 200

TRADE_TABLE

Account Security Trade_Quantity
1 A 50
2 C 10

我想以匹配行显示为一行的方式连接它们,但不匹配的行也会显示,因此标准 LEFT JOIN 不起作用。

预期输出:

Account Security Pos_Quantity Trade_Quantity
1 A 100 50
2 B 200 0
2 C 0 10

我该怎么做?

完整的外部联接在这里可以很好地工作:

with position_table as (select 1 account, 'A' security, 100 pos_quantity from dual union all
                        select 2 account, 'B' security, 200 pos_quantity from dual),
        trade_table as (select 1 account, 'A' security, 50 trade_quantity from dual union all
                        select 2 account, 'C' security, 10 trade_quantity from dual)                   
select coalesce(pt.account, tt.account) account,
       coalesce(pt.security, tt.security) security,
       coalesce(pt.pos_quantity, 0) pos_quantity,
       coalesce(tt.trade_quantity, 0) trade_quantity
from   position_table pt
       full outer join trade_table tt on pt.account = tt.account
                                         and pt.security = tt.security
order by account,
         security;

db<>fiddle - 请注意您如何看到完整的外部联接与 where 子句中定义的子查询一起工作得很好!