0

ここに 2 つのテーブルがあります。私が欲しいのは、これら2つのテーブル内の金額と残高を計算(加算)することです。しかし難しいのは、トランザクション テーブルで 2 つの account_no が同じ (A-102) であることです。では、 when = ??にどのように追加amountするのですか?balancetransactions.account_idaccount.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 に答える