2016-12-06 95 views
1

enter image description hereAccess查询减去2不同的列从不同的行中相同的表相同的ID

我有一个表deposit具有柱Refund_amtDeposit_amt具有相同GR_no不同的行。在这里我的问题是,我想从Refund_amt 减去deposit_amt专栏中,我尝试过各种替代在查询,但没有成功

我的查询:

SELECT d.Gr_no 
    , d.Rec_No 
    , d.Deposite_Amt 
    , d.penalty_Amt 
    , d.Refund_Amt - Refund 
    , s.Name 
    , s.cur_std 
    , cur_div 
    From 
    (select d.Refund_Amt refund 
     from deposite d 
      , std_gr s 
     where d.Gr_no = s.Gr_no ) 

结果应该是这样的final total列:

enter image description here

谢谢

+2

你能给我想要的结果吗 –

回答

1

您正在寻找每std_gr的聚合:存款总和减去退款总和。一种方法是在子查询中进行这种聚合,并将此子查询加入到您的表中。

select 
    d.*, sums.final_total 
from deposite d 
join 
(
    select std_gr, nz(sum(deposite_amt),0) - nz(sum(refund_amt),0) as final_total 
    from deposite 
    group by std_gr 
) as sums on sums.std_gr = d.std_gr 
order by d.rec_no; 
+0

谢谢.yeah我真的只想这个 – Mamta