我有两张桌子,一张兴趣桌和一张收费表。利息表已借记利息和信贷利息我已经能够使用此查询获得差异:
select e.sol_id, (sum(CASE WHEN e.INTEREST_IND = 'D' THEN e.AMOUNT_IN_LCY ELSE 0 END)-
sum(CASE WHEN e.INTEREST_IND = 'C' THEN e.AMOUNT_IN_LCY ELSE 0 END)) as Difference
from tbaadm.INTEREST_DETAILS e
group by e.sol_id;
我的输出是正确的:
我现在需要在Charges表中添加这样的金额,我试过这样:
select e.sol_id, (sum(CASE WHEN e.INTEREST_IND = 'D' THEN e.AMOUNT_IN_LCY ELSE 0 END)-
sum(CASE WHEN e.INTEREST_IND = 'C' THEN e.AMOUNT_IN_LCY ELSE 0 END) +
sum(f.AMOUNT_IN_LCY)) as Difference
from tbaadm.INTEREST_DETAILS e,TBAADM.CHARGE_DETAILS f
where F.SOL_ID = E.SOL_ID
group by e.sol_id, f.sol_id
挂起片刻后的这个查询给出了这个输出:
哪个错误考虑到从第一个表中的信用中减去借方有分支000,001和003的条目时,即使第二个表没有条目,如何从第二个表中添加金额并维护我的结果集分支000和003?
答案 0 :(得分:2)
我认为你需要一个外部联接。
你基本上有两个像这样的数据集:
Set1: ID VAL Set2: ID Val => Expected Result:
1 10 1 5 1 15
2 20 2 20
3 30 3 30
所以你需要一个正确的外部联接
对于你的SQL,它将是:
select e.sol_id
,(sum(CASE WHEN e.INTEREST_IND = 'D' THEN e.AMOUNT_IN_LCY ELSE 0 END)
- sum(CASE WHEN e.INTEREST_IND = 'C' THEN e.AMOUNT_IN_LCY ELSE 0 END)
+ sum(f.AMOUNT_IN_LCY)
) as Difference
from tbaadm.INTEREST_DETAILS e
,tbaadm.CHARGE_DETAILS f
where E.SOL_ID = F.SOL_ID (+)
group by e.sol_id, f.sol_id;
(+)表示表,也可以为NULL。另一种写作方式是:
select e.sol_id
,(sum(CASE WHEN e.INTEREST_IND = 'D' THEN e.AMOUNT_IN_LCY ELSE 0 END)
- sum(CASE WHEN e.INTEREST_IND = 'C' THEN e.AMOUNT_IN_LCY ELSE 0 END)
+ sum(f.AMOUNT_IN_LCY)
) as Difference
from tbaadm.INTEREST_DETAILS e
LEFT OUTER JOIN
tbaadm.CHARGE_DETAILS f
ON E.SOL_ID = F.SOL_ID
group by e.sol_id, f.sol_id;
第二版符合SQL标准,而第一版(+)仅受Oracle支持。