mysql - MySQL从前几行添加余额
问题描述
我已经尝试了一些我在这里看到的东西,但在我的情况下它不起作用,每一行的余额似乎重复。
无论如何,我有一个保存抵押交易的表,该表有一个存储利息附加值或支付值的列。
所以我可能有:
Balance: 100,000
Interest added 100 - balance 100,100
Payment made -500 - balance 99,600
Interest added 100 - balance 99,700
Payment made -500 - balance 99,200
我正在寻找的是一个查询,以最新的日期顺序提取所有这些,并根据它是否有利息或付款(不会为空的那个)将余额汇总在一列中,所以在最后它将承担当前责任的行
我不记得我尝试过的查询是什么,但它最终重复了行并且余额很奇怪
样本结构和数据:
CREATE TABLE account(
id int not null primary key auto_increment,
account_name varchar(50),
starting_balance float(10,6)
);
CREATE TABLE account_transaction(
id int not null primary key auto_increment,
account_id int NOT NULL,
date datetime,
interest_amount int DEFAULT null,
payment_amount float(10,6) DEFAULT NULL
);
INSERT INTO account (account_name,starting_balance) VALUES('Test Account','100000');
INSERT INTO account_transaction (account_id,date,interest_amount,payment_amount) VALUES(1,'2020-10-01 00:00:00',300,null);
INSERT INTO account_transaction (account_id,date,interest_amount,payment_amount) VALUES(1,'2020-10-01 00:00:00',null,-500);
INSERT INTO account_transaction (account_id,date,interest_amount,payment_amount) VALUES(1,'2020-11-01 00:00:00',300,null);
INSERT INTO account_transaction (account_id,date,interest_amount,payment_amount) VALUES(1,'2020-11-05 00:00:00',-500,null);
因此,利息将添加到滚动余额中,并且起始余额存储在帐户中 - 如果我们必须为此添加交易,那么可以。然后,当添加付款时,它可以是负数或正数,以减少移动到每一行的余额。
所以上面的例子我希望看到一些类似的东西:
我希望这会让它更清楚
解决方案
WITH
starting_dates AS ( SELECT id account_id, MIN(`date`) startdate
FROM account_transaction
GROUP BY id ),
combine AS ( SELECT 0 id,
starting_dates.account_id,
starting_dates.startdate `date`,
0 interest_amount,
account.starting_balance payment_amount
FROM account
JOIN starting_dates ON account.id = starting_dates.account_id
UNION ALL
SELECT id,
account_id,
`date`,
interest_amount,
payment_amount
FROM account_transaction )
SELECT DATE(`date`) `Date`,
CASE WHEN interest_amount = 0 THEN 'Balance Brought Forward'
WHEN payment_amount IS NULL THEN 'Interest Added'
WHEN interest_amount IS NULL THEN 'Payment Added'
ELSE 'Unknown transaction type'
END `Desc`,
CASE WHEN interest_amount = 0 THEN ''
ELSE COALESCE(interest_amount, 0)
END Interest,
COALESCE(payment_amount, 0) Payment,
SUM(COALESCE(payment_amount, 0) + COALESCE(interest_amount, 0))
OVER (PARTITION BY account_id ORDER BY id) Balance
FROM combine
ORDER BY id;
PS。提供的源数据(带有 的行id=4
)根据提供的所需输出进行了更改。源结构已更改,FLOAT(10,6)
与提供的值不兼容已替换为DECIMAL
.
聚苯乙烯。允许存在多个帐户。
推荐阅读
- python - Pygame 已安装但 Pycharm 找不到模块
- java - 使用 HTML5 视频标签的 JavaFx 中的全屏视频
- git - Git 中的最新存储、零索引或最大索引是什么?
- python - 将数据的平均值插入新列
- javascript - jsReport 不使用 Highcharts 显示正确的图表名称
- javascript - 在我的终端中输入什么,以便我的 Javascript express 可以连接到 localhost:3000,并在终端控制台上打印出中间件?
- speech-recognition - 有没有办法通过 ms 说话人识别将 MS 语音与文本接口?
- ffmpeg - 使用 ffmpeg 合并片段会导致音频出现小裂缝
- jquery - Kendo UI JQuery 的渲染问题 - IE 上的甘特图
- redis - 如何远程执行 Redis 命令