我有一张桌子transactions
在我的 MySQL 数据库中,有 50K 条记录。数据如下所示。
trx_date bill due
2020-03-01 100.00 10.00
2020-03-02 50.00 20.00
2020-03-02 100.00 0.00
2020-03-03 200.00 30.00
2020-03-04 100.00 10.00
...
...
我的目标是用查询参数显示查询结果from_date
and to_date
从开桌开始日期起为0,计算为
opening(+) bill (+) due (-) closing = ( opening+bill ) - due
trx_date opening bill due closing
2020-03-01 0 100.00 10.00 90.00
2020-03-02 90.00 50.00 20.00 120.00
2020-03-02 120.0 100.00 0.00 220.00
2020-03-03 220.00 200.00 20.00 400.00
2020-03-04 400.00 110.00 10.00 500.00
....
....
我不知道获取上一个日期的最佳方式是什么closing
对于我选择的 from_dateopening
.
from_date=2020-03-03
and to_date=2020-03-04
trx_date opening bill due closing
2020-03-03 220.00 200.00 20.00 400.00
2020-03-04 400.00 110.00 10.00 500.00
我的观点是如何打开220.00
从之前的结果来看?为了从之前的结果中获取 220.00,可能会有数千条记录,那么最佳实践是什么?
您需要计算所有opening
and closing
从第一个开始的值trx_date
,然后按您感兴趣的日期过滤结果:
SELECT trx_date, opening, bill, due, closing
FROM (
SELECT trx_date,
@balance AS opening,
bill,
due,
@balance := @balance + bill - due AS closing
FROM transactions
CROSS JOIN (SELECT @balance := 0) ini
ORDER BY trx_date
) tx
WHERE trx_date BETWEEN '2020-03-03' AND '2020-03-04'
Output:
trx_date opening bill due closing
2020-03-03 220 200 20 400
2020-03-04 400 110 10 500
dbfiddle 上的演示
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)