2013-03-04 1 views
0

여기에 두 개의 테이블이 있습니다. 내가 원하는 것은이 두 테이블 내에서 금액과 잔액을 계산 (추가)하는 것입니다. 그러나 어려운 것은 거래 테이블에서 두 account_no가 동일하다는 것입니다 (A-102). 그래서 transactions.account_id = account.account_no = A-102 일 때 amountbalance에 어떻게 추가할까요 ?? 내가 무슨 짓을sql 다른 테이블로 여러 레코드를 계산하십시오.

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을 작동합니다. I는 다음과 같이 작성하는 경우가 작동하지 않습니다 ..

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

계좌 번호로 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' 
+0

와우, 확실히 작동 할 수 있습니다. 감사합니다. 그러나'account-no '라는'A-102','A-222','A-305'를 출력하고'account' 테이블의 다른 레코드도 원한다면 어떻게할까요? @rs. – Sunny

+0

@Sunny, 내 업데이트 된 답변을 확인하고, 왼쪽 외부 조인으로 내부 조인을 변경하고 금액에 잔액을 추가 할 때 금액이 null인지 확인하십시오. –

+0

Yh, 완전히 작동합니다. 고맙습니다. 할 일이 있습니다.해야합니다. 그것에 관한 약간의 연구. 그것은 나를 위해 새로운 것입니다. 롤 @rs. – Sunny