我开发了以下SQL。基本上有2个表。在本SQL的第一部分中,我将table 1
加入table 2
并提取table 1
中的所有记录以及table 1
的匹配记录。然后,我对UNION
做同样的事情,但这一次,我将table 2
加入table 1
,并从table 2
中提取所有记录并仅匹配来自table 1
的记录。
查询的每一半中的UNION
是这样我可以在同一列中同时获得固定资产帐户和累计折旧帐户。
我需要这样做,因为table 1
而不是table 2
中可能有数据,我需要确保我得到所有的差异。正如我所料,结果中返回了重复的行。我有几个问题:
如何摆脱重复的结果?
我计算查询的每一半的差异。是否有更好的方法或地点进行此计算?
这是一种更好的方法吗?
感谢您对这些问题的帮助?
SELECT
a.FA_ACCT,
a.ERACBR,
a.deptid,
a.FA_AMT,
pgal.pstd_ttl_amt,
CASE WHEN pgal.pstd_ttl_amt IS NULL THEN a.FA_AMT
ELSE a.FA_AMT - pgal.pstd_ttl_amt END AS DIFF
FROM
(SELECT
pdr.account_fa AS FA_ACCT,
ir.erac_branch_lgcy_cd AS ERACBR,
pdr.deptid,
SUM(pdr.COST) AS FA_Amt
FROM PSFS.PS_DEPR_RPT pdr
LEFT JOIN INTGRT_RPT.DIM_LOCATION ir ON pdr.deptid = ir.erac_branch_ps_org_cd AND ir.curr_lrd_row_flg = 1
WHERE pdr.BUSINESS_UNIT = 'A0465'
AND pdr.BOOK = 'PERFORM'
AND pdr.FISCAL_YEAR = 2015
AND pdr.ACCOUNTING_PERIOD = 8
AND pdr.GROUP_ASSET_FLAG <> 'M'
--AND ( ? is null or soh.REGION_CD = ?)
GROUP BY FA_ACCT, ERACBR, deptid
UNION All
SELECT
pdr.account_ad AS FA_ACCT,
ir.erac_branch_lgcy_cd AS ERACBR,
pdr.deptid,
SUM(pdr.depr_ltd) AS FA_Amt
FROM PSFS.PS_DEPR_RPT pdr
LEFT JOIN INTGRT_RPT.DIM_LOCATION ir ON pdr.deptid = ir.erac_branch_ps_org_cd AND ir.curr_lrd_row_flg = 1
WHERE pdr.BUSINESS_UNIT = 'A0465'
AND pdr.BOOK = 'PERFORM'
AND pdr.FISCAL_YEAR = 2015
AND pdr.ACCOUNTING_PERIOD = 8
AND pdr.GROUP_ASSET_FLAG <> 'M'
--AND ( ? is null or soh.REGION_CD = ?)
GROUP BY FA_ACCT, ERACBR, deptid ) a
LEFT JOIN PSFS.PS_GL_ACCT_LDGR PGAL ON a.deptid =pgal.grp_br_ps_org_id
AND a.fa_acct = pgal.acct_nbr
AND pgal.fiscal_yr_mth_nbr = 201508
GROUP BY 1,2,3,4,5,6
UNION ALL
SELECT
pgal.acct_nbr AS FA_ACCT,
ir.erac_branch_lgcy_cd AS ERACBR,
pgal.grp_br_ps_org_id,
b.FA_AMT,
pgal.pstd_ttl_amt,
CASE WHEN b.fa_amt IS NULL THEN pgal.pstd_ttl_amt
ELSE b.FA_AMT - pgal.pstd_ttl_amt END AS DIFF
FROM psfs.ps_gl_acct_ldgr pgal
LEFT JOIN INTGRT_RPT.DIM_LOCATION ir ON pgal.grp_br_ps_org_id = ir.erac_branch_ps_org_cd AND ir.curr_lrd_row_flg = 1
LEFT JOIN
(SELECT
pdr.account_fa AS FA_ACCT,
pdr.deptid,
SUM(pdr.COST) AS FA_Amt
FROM PSFS.PS_DEPR_RPT pdr
WHERE pdr.BUSINESS_UNIT = 'A0465'
AND pdr.BOOK = 'PERFORM'
AND pdr.FISCAL_YEAR = 2015
AND pdr.ACCOUNTING_PERIOD = 8
AND pdr.GROUP_ASSET_FLAG <> 'M'
--AND ( ? is null or soh.REGION_CD = ?)
GROUP BY FA_ACCT, deptid
UNION All
SELECT
pdr.account_ad AS FA_ACCT,
pdr.deptid,
SUM(pdr.depr_ltd) AS FA_Amt
FROM PSFS.PS_DEPR_RPT pdr
WHERE pdr.BUSINESS_UNIT = 'A0465'
AND pdr.BOOK = 'PERFORM'
AND pdr.FISCAL_YEAR = 2015
AND pdr.ACCOUNTING_PERIOD = 8
AND pdr.GROUP_ASSET_FLAG <> 'M'
--AND ( ? is null or soh.REGION_CD = ?)
GROUP BY FA_ACCT, deptid) b
ON pgal.grp_br_ps_org_id = b.deptid
AND pgal.acct_nbr = b.fa_acct
WHERE pgal.fiscal_yr_mth_nbr = 201508
AND pgal.acct_nbr BETWEEN 130500 AND 160500
AND ir.ody_group_cd = 'A0465'
ORDER BY 1, 2