Sum from multiple tables

R

Rusty Jones

I have three tables:
Accounts - store an id and information about the account.
External Transfer - stores an account id and the amount transfered into the
account
Internal Transfer - transfer from one account to another (from account, to
account, and amount)

I want a query that computes the balance in each account. The balance is
the sum of all the external transfers plus the internal transfers into the
account minus the internal transfers that go from the account.

Any time I try to build a query to do this I end up with some of the values
used twice.

Any ideas?
 
J

John Spencer

This looks as if you will need to use subqueries in the SELECT clause.

SELECT Accounts.AccountID
, SUM (Amount) as ExternalSum
, (SELECT Sum(Amount)
FROM InternalTransfer
WHERE InternalTransfer.FromAccount= Accounts.AccountID) as InternalOut
, (SELECT Sum(Amount)
FROM InternalTransfer
WHERE InternalTransfer.ToAccount= Accounts.AccountID) as InternalIn
FROM Accounts LEFT JOIN ExternalTransfer
ON Accounts.AccountID =ExternalTransfer.AccountID
GROUP BY Accounts.AccountID
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top