4

I want to run a select statement that includes a sum from another table. I know I will probably have to setup a join but I'm not sure how to approach it.

I want to select a list of accounts then get their balances(sum from another table) This is the idea I have been going in but obviously its not correct.

SELECT
    account_name
FROM
    tblaccounts
    JOIN (
        SELECT
            SUM(balance) AS account_balance
        FROM
            tblinvoices
    ) t ON t.account_id = tblaccount_account_id
WHERE
    tblaccounts.account_id = 1

desired output

Name   |   balance
------------------
Account1      50
Account2     100

2 Answers 2

11

Try

SELECT account_name, SUM(balance) balance
 FROM tblaccounts a LEFT JOIN tblinvoices i
   ON a.account_id = i.tblaccount_account_id
WHERE a.customer_id = 1
GROUP BY account_id

Output:

| ACCOUNT_NAME | BALANCE |
--------------------------
|     Account1 |      50 |
|     Account2 |     100 |

Here is SQLFiddle demo

Sign up to request clarification or add additional context in comments.

2 Comments

You are very welcome :) If it was what you were looking for please, consider to accept the answer.
Why is it left join and not just join?
1

You will need to create sub-queries to isolate each SUM otherwise you will return a SUM of every balance, not one for each. And it will be one row, not a row for each account.

SELECT 
     a.account_name,
    (
      SELECT SUM(i.balance) 
      FROM tblinvoices AS i 
      WHERE a.account_id = i.tblaccount_account_id
    ) AS balance
FROM tblaccounts AS a;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.