【问题标题】:Aggregation record with left outer join带有左外连接的聚合记录
【发布时间】:2016-06-20 13:52:50
【问题描述】:

我想聚合两个表之间的记录,例如下面我尝试使用 TB_SRS_MST 表进行左外连接,但我得到了想要的结果。基本上我想为 TB_DLR_STS 表中不存在的每个系列显示“-”。

TB_DLR_STS 表

 DLR_CD  SRS_CD   STS
    D1    S1        Y
    D1    S2        N
    D2    S2        Y
    D2    S3        Y
    D3    S1        N

TB_STS_MST 表

SRS_CD  
  S1    
  S2    
  S3    
  S4    

期望的输出

DLR_CD  SRS_CD  STS
D1      S1      Y
D1      S2      N
D1      S3      -
D1      S4      -
D2      S1      -
D2      S2      Y
D2      S3      Y
D2      S4      -
D3      S1      N
D3      S2      -
D3      S3      -
D3      S4      -

【问题讨论】:

  • S4 来自哪里?
  • 很抱歉更正了 TB_SRS_MST 记录

标签: sql oracle


【解决方案1】:

我假设TB_STS_MST 表中的数据实际上应该更像这样:

SRS_CD  
S1    
S2    
S3    
S4

假设是这样,首先您需要定义您想要的列表——您可以通过创建带有cross joincartesian product 来做到这一点。然后你可以使用outer joincoalesce

select t.dlr_cd, t.srs_cd, coalesce(ds.sts, '-') sts
from (
   select distinct ds.dlr_cd, sm.srs_cd
   from TB_DLR_STS ds cross join TB_STS_MST sm
) t left join TB_DLR_STS ds on t.dlr_cd = ds.dlr_cd 
                           and t.srs_cd = ds.srs

【讨论】:

  • @user2101952 如果这个答案解决了你的问题,你能接受吗?
【解决方案2】:

可以通过左分区连接来完成。

select tb_dlr_sts.dlr_cd,
       tb_sts_mst.srs_cd,
       nvl(tb_dlr_sts.sts, '-') as sts
  from tb_sts_mst
       left join tb_dlr_sts partition by (tb_dlr_sts.dlr_cd) on tb_dlr_sts.srs_cd = tb_sts_mst.srs_cd

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多