具有左外连接的聚合记录

时间:2016-06-20 13:52:50

标签: sql oracle

我想在两个表之间汇总记录,例如下面我尝试使用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      -

2 个答案:

答案 0 :(得分:0)

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

SRS_CD  
S1    
S2    
S3    
S4

假设是这样,首先您需要定义所需的列表 - 您可以通过创建cartesian product cross join来实现此目的。然后,您可以outer join使用coalesce

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

答案 1 :(得分:0)

可以使用左分区连接完成。

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