SQL query for calculating account balance

放肆的年华 提交于 2019-12-02 13:44:38

You are basically calculating the cross product between a tdebits and tcredits, i.e. for each row in tdebits you are iterating over all the rows in tcredits. There's also no reason to join to accounts (unless to_account_id and from_account_id aren't foreign keys).

You only need to do one pass over transactions and you just need to know whether the amount is a credit or debit.

SELECT SUM(CASE WHEN t.to_account_id = $1 THEN t.amount ELSE -t.amount END) AS amount
FROM transactions AS t
WHERE (t.to_account_id = $1 OR t.from_account_id = $1)
  AND t.succeed = true

If an account can transfer to itself, add a t.to_account_id <> t.from_account_id.

Aggregate before doing the joins, if you want the value for all accounts:

select a.*, coalesce(tdebit.debit, 0) - coalesce(tcredit.credit, 0)
from accounts a left join
     (select t.to_account_id, sum(t.amount) as debit
      from transactions t
      group by t.to_account_id
     ) tdebit
     on a.id = tdebit.to_account_id left join
     (select t.from_account_id, sum(t.amount) as credit
      from transactions t
      group by t.from_account_id
     ) tcredit
     on a.id = tcredit.from_account_id;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!