SQL计算账户余额的查询

SQL query for calculating account balance

我想使用原始 sql 计算帐户余额,无需额外的应用程序逻辑。 交易模式包括金额、from_account_id 和 to_account_id

我的查询是

SELECT SUM(tdebit.amount) - SUM(tcredit.amount) as balance
FROM accounts as a
INNER JOIN transactions as tdebit ON a.id = tdebit.to_account_id
INNER JOIN transactions as tcredit ON a.id = tcredit.from_account_id
WHERE a.id =  AND tdebit.succeed = true AND tcredit.succeed = true

它并没有像我预期的那样工作——结果是错误的,但是如果我只在它正常工作后才加入交易,例如只需要借记金额就可以了

SELECT SUM(tdebit.amount) as debit
FROM accounts as a
INNER JOIN transactions as tdebit ON a.id = tdebit.to_account_id
WHERE a.id =  AND tdebit.succeed = true

我在余额查询中遗漏了什么?

http://sqlfiddle.com/#!15/b5565/1

您基本上是在计算 tdebitstcredits 之间的叉积,即对于 tdebits 中的每一行,您正在迭代 tcredits 中的所有行。也没有理由加入 accounts(除非 to_account_idfrom_account_id 不是外键)。

您只需要进行一次转账交易,您只需要知道金额是贷方还是借方即可。

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

如果账户可以转账给自己,加一个t.to_account_id <> t.from_account_id

如果您想要所有帐户的值,请在进行联接之前进行聚合:

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;