简体   繁体   中英

How to get SUM of a column of a child table when query parent table?

I have two tables

Account Table (account)

id      name
1       Account 1
2       Account 2
3       Account 3
4       Account 2

Transaction Table (transaction)

id      account_id     type      amount     datetime
1       1              credit    500        2020-04-01 06:00:00
2       1              credit    300        2020-04-01 06:00:00
3       2              credit    100        2020-04-01 06:00:00
4       2              debit     50         2020-04-01 06:00:00
5       1              debit     600        2020-04-01 06:00:00
6       3              credit    1000       2020-04-01 06:00:00
7       1              credit    100        

My target is to get account id, name, balance in one query. The balance will be calculated from the transaction table as SUM of Credit Amount - SUM of Debit Amount for a given account.

Target Output

   id      name          balance
   1       Account 1     300
   2       Account 2     50
   3       Account 3     1000
   4       Account 4     0

Possible Query

SELECT id, name, ((SELECT SUM(amount) FROM transaction WHERE type = 'credit' AND account_id = {ACCOUNT_ID} ) - (SELECT SUM(amount) FROM transaction WHERE type = 'debit' AND account_id = {ACCOUNT_ID} )) as balance

Is it possible to do this in one query and If yes How to do it.

You could do the aggregation in a derived table to avoid the issues of having to group by a lot of fields in the top level. For example:

SELECT a.id, a.name, COALESCE(b.balance, 0) AS balance
FROM account a
LEFT JOIN (
  SELECT account_id,
         SUM(CASE WHEN type='credit' THEN amount ELSE 0 END) -
         SUM(CASE WHEN type='debit' THEN amount ELSE 0 END) AS balance
  FROM transaction
  GROUP BY account_id
) b ON b.account_id = a.id

Output:

id  name        balance
1   Account 1   300
2   Account 2   50
3   Account 3   1000
4   Account 2   0

Demo on SQLFiddle

You need a left join of account to transaction so you can group by each account and conditionally sum the amount depending on the type :

select 
  a.id, a.name,
  sum(case when type = 'credit' then 1 else -1 end * coalesce(t.amount, 0)) balance
from account a left join transaction t
on t.account_id = a.id
group by a.id, a.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM