sql - 从两个表中计算用户账户余额
问题描述
我有两张桌子:
1 付款表
PID Amount IsOk
=======================
10 50 true
10 92 false
14 73 true
14 22 true
15 10 true
2 取款表
PID Amount IsOk
=======================
10 23 true
14 98 false
14 15 true
我想要subtract(sum of withdraws amounts) and (sum of withdraws amounts) where IsOk=true
这样的任何PID
PID Balance
=======================
10 27 //50-23
14 80 //73+22-15
15 10 //10
解决方案
一种选择使用union all
和聚合:
select pid, sum(amount) balance balance
from (
select pid, amount from payment where isOk = 'true'
union all
seect pid, -amount from withdraws where isOk = 'true'
) t
group by pid
推荐阅读
- python - Python 更改计算器变量放置
- python - How to get value from the output of a weighing scale
- ruby - What does ‘execute_script(script, *args)' mean in ruby Selenium web driver
- swift - How to create the operator "|>" to sort the collection [2,5,3,4] from least to greatest on swift
- elasticsearch - Elasticsearch:更喜欢前缀匹配而不是术语匹配
- matplotlib - Create a LinearSegmentedColormap with values within range
- arrays - 如何编写 N1QL 查询以获取所有 ordrqty 等于 102 的 SaleDt1
- node.js - 从 firebase 实时数据库中删除
- javascript - 尝试构建 React-Admin,不断收到“编辑 src/App.js 并保存以重新加载”
- asp.net-web-api - 我尝试使用 IApplicationBuilder 制作 Asp.net Api,而不是 asp.net 核心