在Oracle select Statement中减去分组数字

时间:2014-03-10 08:36:27

标签: sql oracle

我有兴趣表,兴趣指标为信用卡或借记卡。要求是获得分支机构的信用卡和借记卡利息分组之间的差异。我的分开查询是:

select sol_id, sum(AMOUNT_IN_LCY)DEBIT_INTEREST from INTEREST_DETAILS where INT_ID = 'D' group by sol_id;

我的另一个问题是:

select sol_id, sum(AMOUNT_IN_LCY)CREDIT_INTEREST from INTEREST_DETAILS where INT_ID = 'C' group by sol_id;

我完全坚持将两个查询添加或减去一个按sol_id分组的resultSet。有任何想法吗??有没有办法先减去数字,然后将它们分组?

3 个答案:

答案 0 :(得分:1)

试试这个:

select sol_id, ABS(sum(DECODE(INT_ID, 'D', -1, 1) * AMOUNT_IN_LCY)) DIFFERENCE 
  from INTEREST_DETAILS
 group by sol_id

它会为您提供每个sol_id的借记和赠送金额之间的差异。

答案 1 :(得分:1)

试试这个:

select t1.sol_id,
sum(t1.DEBIT_INTEREST)DEBIT_INTEREST,sum(t1.CREDIT_INTEREST)CREDIT_INTEREST
FROM
(select sol_id, 
case when INT_ID = 'D' then AMOUNT_IN_LCY else 0 end DEBIT_INTEREST,
case when INT_ID = 'C' then AMOUNT_IN_LCY else 0 end CREDIT_INTEREST
from INTEREST_DETAILS)t1  group by t1.sol_id;

答案 2 :(得分:1)

select sol_id, (sum(CASE WHEN INT_ID = 'C' THEN AMOUNT_IN_LCY ELSE 0 END)-
sum(CASE WHEN INT_ID = 'D' THEN AMOUNT_IN_LCY ELSE 0 END)) as Difference 
from INTEREST_DETAILS  
group by sol_id;