MySQL带有日期范围的期初余额

问题描述 投票:0回答:1

我在MySQL数据库中有一个表transactions,记录有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_dateto_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
....
....

我不知道为我选择的from_date closing获取上一个日期opening的最佳方法是什么。

[from_date=2020-03-03to_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,可能会有成千上万的记录,因此最佳实践是什么?

mysql sql
1个回答
0
投票

正式:

SELECT @balance opening, bill, due, @balance := @balance + bill - due closing
FROM source_table, (SELECT @balance := 0) variable
/* ORDER BY trx_date */
;

但是显示的样本数据中没有唯一的标准-因此结果不具有确定性。

© www.soinside.com 2019 - 2024. All rights reserved.