0

我这里有两张桌子。我想要的是计算(添加)这两个表中的金额和余额。但困难在于事务表中的两个account_no 相同(A-102)。那么如何添加amountbalancewhen transactions.account_id= account.account_no = A-102??

这是交易表

账户表

我所做的是:

    select account_no, balance + (
                              select t.amount
                              from transactions t
                              where t.account_no = 'A-222')
    from b_account 

    where account_no = 'A-222';

此方法仅适用于 A-305 和 A-222。这么写就不行了。。

select account_no, balance + (
                              select t.amount
                              from transactions t
                              where t.account_no = (
                                                    select t.account_no 
                                                    from b_account ba, transactions t
                                                    where ba.account_no = t.account_no
                                                    )      
                              )
from b_account 
where account_no = (select t.account_no 
                    from b_account ba, transactions t
                    where ba.account_no = t.account_no);

任何帮助,谢谢!

4

1 回答 1

1

您可以group按帐号和sum所有金额,然后将结果加入帐户表。试试这个

with cte as
(
 select account_no, SUM(t.amount) amount
 from transactions t
 --where t.account_no = 'A-222'
 group by account_no
)

Select a.account_no, balance + coalesce(b.amount,0) new_balance
from b_account a
left outer join cte b on a.account_no = b.account_no
--where a.account_no = 'A-222'
于 2013-03-04T17:51:02.913 回答