2013-03-04 45 views
0

我在这里有两个表格。我想要的是在这两个表格内计算(添加)数量和平衡。但困难在于交易表中的两个account_no是相同的(A-102)。那么如何在transactions.account_id = account.account_no = A-102时将amount加到balancesql与另一个表格计算多个记录

This is transactions table

The account table

我所做的是:

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); 

任何帮助的感谢!先进

回答

1

您可以通过帐号groupsum所有金额,然后将结果加入帐户表。试试这个

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' 
+0

哇,它绝对可以工作。非常感谢它..但它只是输出'A-102','A-222','A-305'这三个'account_no',如果我还想从'account'表中输入其他记录呢? @rs。 – Sunny 2013-03-04 18:05:32

+0

@Sunny,检查我更新的答案,将内部连接更改为左外部连接,并确保当您将余额添加到金额为 – 2013-03-04 18:07:38

+0

时,检查金额是否为零。Yh,它完全正常工作。谢谢你lotttt ..我必须做的对它进行一些研究。对我来说这是一件新事物。大声笑。 – Sunny 2013-03-04 18:43:09

相关问题