表1中的所有行和表2中的匹配行

时间:2015-05-07 21:04:16

标签: sql join teradata

下面代码的第一部分为我提供了正确的记录数量和数量(776)。当我加入表b时,代码运行但没有提供我正在寻找的答案。问题是第二个表不包含我从第一个查询中获得的所有部门/帐户组合。

我要做的是显示第一个表中的所有记录,无论第二个表中是否匹配。如果组合在表2中,那么我将获得金额。我试图使用不同的连接(左,外,右,右外)没有任何运气。所有连接都给我相同数量的记录(412)而不是776,因为它在Branch上匹配。

如果表2中有记录,我怎样才能更改此内容以获取查询第一部分的所有记录。再次感谢您的所有帮助......

SELECT
    a.Account,
    a.Branch,
    a.Department,
    a.Amount,
    b.Total_Amount, 
    a.Amount - b.Total_Amount as DIFF

FROM 

    (SELECT 
        pdr.account_fa AS Account,
        ir.branch_lgcy_cd AS Branch,
        pdr.Department,
        sum(pdr.COST) AS Amount

    FROM PSFS.DEPR_RPT pdr 

    INNER JOIN INTGRT_RPT.DIM_LOCATION ir ON pdr.Department = ir._branch_ps_org_cd AND ir.curr_lrd_row_flg = 1

    WHERE pdr.BUSINESS_UNIT = 'A5'
    AND pdr.FISCAL_YEAR = 2015
    AND pdr.ACCOUNTING_PERIOD = 8

    GROUP BY Account, Branch, department

    UNION ALL

    SELECT
    pdr.account_ad AS Account,
    ir.erac_branch_lgcy_cd AS Branch,
    pdr.Department,
    sum(pdr.depr_ltd) AS Amount

    FROM PSFS.PS_DEPR_RPT pdr 

    LEFT JOIN INTGRT_RPT.DIM_LOCATION ir ON pdr.Department = ir.branch_ps_org_cd AND ir.curr_lrd_row_flg = 1

    WHERE pdr.BUSINESS_UNIT = 'A5'
    AND pdr.FISCAL_YEAR = 2015
    AND pdr.ACCOUNTING_PERIOD = 8

    GROUP BY Account, Branch, Department ) a

INNER JOIN PSFS.PS_GL_ACCT_LDGR b ON a.deptid = b.grp_br_ps_org_id 
    AND a.fa_acct = b.acct_nbr
    AND b.fiscal_yr_mth_nbr = 201508

GROUP BY Account, Branch, Department, Amount, Total_Amount

ORDER BY 1, 2

1 个答案:

答案 0 :(得分:0)

INNER JOIN PSFS.PS_GL_ACCT_LDGR b ON a.deptid将此更改为LEFT OUTER JOIN