从2个表中减去总计

时间:2014-01-08 18:20:57

标签: sql-server

我有2张存款和提款表

Deposit Table:
AccountNumber  Amount
1               200
1               400
1               150
           Total=750

Withdrawal Table:
AccountNumber  Amount
1               100
1               300
1               150
           Total=550

我需要一个查询来汇总每个表的总和。减去(存款 - 取款)Group BY AccountNumber为(750-550)= 200类似:

TotalBalance Table:
AccountNumber  Amount
1               200

我试过Karamafrooz答案

选择SUM(d.Ammount) - SUM(w.Ammount) 从存款作为内部联接WithDrawal作为w 在d.AccountNumber = w.AccountNumber 按d.AccountNumber分组

但我的错误值

抱歉,现在我有第3个表叫做Profit:

Profit Table:
AccountNumber  Amount
1               100
1               200
1               150
           Total=450

我需要总额(存款+利润提取) 我怎样才能做到这一点? jim31415解决方案适用于第一种情况

1 个答案:

答案 0 :(得分:2)

这使用子查询来获取每个表中每个帐户的总计。然后它总结金额。请注意,提款金额被否定,总和(-d.Amount)

select 
   AccountNumber,
   sum(Amount) as Balance
from (
   select d.AccountNumber as AccountNumber, sum(d.Amount) as Amount from Deposit d group by d.AccountNumber
   union
   select d.AccountNumber, sum(-d.Amount) from Withdrawal d group by d.AccountNumber
) as t
group by AccountNumber