mysql - MySql 获取账户余额
问题描述
我想计算 3 个账户的余额。
我有 2 张桌子:
- 具有id、name和start-balance 的帐户
- 交易价值,收费帐户,类型和支付
要计算余额,我必须将起始余额(来自账户)与所有交易值相加,其中charge-account = account-id,paid = 1 和type = 1。然后我必须减去(正确的词?)所有Charge-account = account-id,paid = 1 和type = 0的交易值
最后,如果一切正常,我只想看看账户现在有多少余额。
我尝试了这个查询,但我得到了错误的结果,看起来它多次添加了 start-balance ...
SELECT
SUM(IF(a.id = 1, IF(t.type = 1 AND t.charge_account = 1, t.value, 0) - IF(t.type = 0 AND t.charge_account = 1, t.value, 0), 0) + a.start-balance) as "balanc_1",
SUM(IF(a.id = 2, IF(t.type = 1 AND t.charge_account = 2, t.value, 0) - IF(t.type = 0 AND t.charge_account = 2, t.value, 0), 0) + a.start-balance) as "balance_2",
SUM(IF(a.id = 3, IF(t.type = 1 AND t.charge_account = 3, t.value, 0) - IF(t.type = 0 AND t.charge_account = 3, t.value, 0), 0) + a.start-balance) as "balance_3"
FROM test.transactions t, test.accounts a
WHERE t.paid = 1;
交易:
帐户:
它应该是怎样的:
解决方案
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
推荐阅读
- javascript - WebdriverIO - 选择器中的 OR 逻辑运算符
- python - 无法在 PyTube 中显示进度条
- python - 使用 django 自定义过滤器进行迭代
- python - 如何从 python 套接字中读取整数?
- vue.js - Vue.js:路由发生变化,但其相应的组件未呈现。控制台中没有错误
- postgresql - 带有可选单词的 websearch_to_tsquery
- javascript - 如何在 React 中为动态渲染的组件设置状态变量
- html - mdbootstrap 表单标签与值重叠
- javascript - 如何将 Navbar(logo, View('Home', ... 从 Flask-Nav 模块的徽标转换为可点击的链接
- python - 使用 List Comprehension 创建 PuLP LPConstraint 时出现“KeyError: (0, 'num')”