php - 使用mysql计算trasaction wise balance
问题描述
MySQL 我想执行一个查询,通过该查询我可以通过公式确定 Total Out:
总打开数 = 最后记录(总打开数)+ 总出 - 总入
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(transaction_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,client_id INT NOT NULL
,action_type VARCHAR(12) NOT NULL
,action_amount INT NOT NULL
);
INSERT INTO my_table(client_id,action_type,action_amount) VALUES
(1 ,'credit', 1000),
(1 ,'debit', 100),
(1 ,'credit', 500),
(1 ,'debit', 300),
(2 ,'debit', 1000),
(2 ,'credit', 1200),
(3 ,'debit', 1000),
(3 ,'credit', 1000),
(4 ,'debit', 1000);
我要结果
Transaction_id | Client Id | Credit | Debit | Balance
1 | 1 | 1000 | 0 | 1000
2 | 1 | 0 | 100 | 900
3 | 1 | 500 | 0 | 1400
4 | 1 | 0 | 300 | 1100
解决方案
从 MySQL 8.0 开始,您可以使用窗口函数作为解决方案:
select
transaction_id,
client_id,
if(action_type='credit', action_amount, 0) credit,
if(action_type='debit', action_amount, 0) debit,
sum(if(action_type='credit', action_amount, -action_amount)) over(partition by client_id order by transaction_id) balance
from transactions;
在线运行MySQL
推荐阅读
- proxy - 3proxy - 如果我与子网一起使用,代理将不起作用
- javascript - Vue - 防止项目在网格中拖动
- mysql - Pyspark:将数据帧存储为 MySQL 表列中的 JSON
- azure - 如何使用 sim7600 连接到 Azure IOT 集线器?
- ios - 需要 RealityKit 中 MeshResource/Box 的开始和结束位置
- sqlite - 如何从 NoteStore.sqlite 文件中提取哈希值
- sql - 将 Varchar 列中的所有数据转换为日期格式
- android - 从 Android 11 后台启动的前台服务打开相机
- java - 多对多关系无法删除父级
- reactjs - React Nat 警告:无法对未安装的组件执行 React 状态更新。这是一个无操作,但它表明您的应用程序中存在内存泄漏