MySQL获取帐户余额

时间:2019-02-18 18:48:52

标签: mysql sum

我想计算3个帐户的余额。

我有2张桌子:

  • 具有 id 名称起始余额
  • 的帐户 具有收费帐户类型付费
  • 交易

要计算余额,我必须添加起始余额(来自帐户),并添加交易值,其中收费帐户 = 帐户ID 付费 = 1,类型 =1。然后我必须减去(正确的单词?)所有交易值,其中收费帐户 = 帐户ID 付费 = 1,类型 = 0

最后,如果一切正常,我只想看看帐户现在有什么余额。

我尝试了此查询,但结果却不正确,看来它多次添加了启动余额...

all

交易:

enter image description here

帐户:

enter image description here

应该如何:

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要使用UNION,然后按帐户ID分组

select accountid, sum(amount ) as amount from (
select accountid, startamount as amount from accounts 
union
select accountid, transactionamount from transactions WHERE ....
) t
group by accountid

答案 1 :(得分:0)

SELECT a.id, 
       MAX ( a.`start-balance` ) + 
       SUM ( CASE WHEN t.type = 1 then  t.value
                  WHEN t.type = 2 then -t.value
                  ELSE 0
             END ) as balance
FROM accounts a
JOIN transactions t
  ON a.id = t.`charge-account`
WHERE a.id IN (1,2,3) 
  AND t.paid = 1
GROUP BY id