MYSQL 中按类别分组的每个财政年度的期初和期末余额总和

The sum of Opening and Closing Balances for each Financial Year Grouped by Category in MYSQL

我已经用了三天的时间试图在没有的情况下解决这个问题 avail.I 甚至在这个论坛上也进行了一些搜索,但也失败了。
它可能看起来像重复问题,但老实说,这与其他问题不同。
我的问题是如何获得每个财政年度的余额结转 C/F 和期末余额的总和 loan_id 对于每个日期范围 ie.Financial 年?


transaction_t
Na    loan_id     date       credit_amount     debit_amount
1      1        2017-01-01     5,000            4,000
2      1        2017-05-01     6,000            2,000 
3      2        2017-10-01     1,000            1,500     
4      1        2018-10-30     2,000            400
5      2        2018-11-01     12,00            1,000   
6      2        2019-01-15      1,800            500   
7      1        2019-05-21     100               200      

以上 table 架构及其数据具有 mysql fiddle here
I have also read this thread 仅适用于单个用户。

到目前为止我已经尝试过:

SELECT loan_id,

 SUM(credit)-(SELECT SUM(a.debit) FROM transaction_t a 
   WHERE a.transaction_date 
   BETWEEN '2019-01-01' AND '2020-12-31' AND a.loan_id = loan_id) AS OpeningBalance, 

sum(credit),sum(debit), 
(@OpeningBalance+SUM(credit))-SUM(debit) AS closing_balance  
FROM transaction_t tr
WHERE transaction_date BETWEEN DATE('2019-01-01') AND DATE('2020-12-31') 
GROUP BY loan_id

但是上面没有给出正确的结果,我如何得到这样的结果?
A:查询日期在 2017-01-01 和 2018-12-31 之间

loan_id     opening_balance       sum(credit_amount)     sum(debit_amount)   closing_balance
1           0                     13,000.00                6,400.00           6,600.00 
2           0                     2,200.00                 2,500.00          -300

B:查询日期介于 2019-01-01 和 2020-12-31

loan_id     opening_balance       sum(credit_amount)     sum(debit_amount)   closing_balance
1           6,600                     100.00               200.00            6,500.00 
2           -300                      1,800.00             500.00            1,000

您正在查找条件聚合。

关键是你需要从历史开始扫描table以产生初始余额。然后你只需要调整条件和:

考虑:

SET @start_date = '2017-01-01';
SET @end_date = '2018-12-31';

SELECT
    loan_id,
    SUM(CASE WHEN transaction_date < @start_date THEN credit - debit ELSE 0 END) opening_balance,
    SUM(CASE WHEN transaction_date BETWEEN @start_date AND @end_date THEN credit ELSE 0 END) sum_credit,
    SUM(CASE WHEN transaction_date BETWEEN @start_date AND @end_date THEN debit ELSE 0 END) sum_debit,
    SUM(CASE WHEN transaction_date <= @end_date THEN credit - debit ELSE 0 END) closing_balance
FROM transaction_t
WHERE transaction_date <= @end_date
GROUP BY loan_id

your DB Fiddle中,这个returns:

loan_id opening_balance sum_credit  sum_debit   closing_balance
1       0               13000       6400        6600
2       0               2200        2500        -300

when changing the dates to 2020-2021

loan_id opening_balance sum_credit  sum_debit   closing_balance
1       6600            100         200         6500
2       -300            1800        500         1000

注意: 是一个问得很好的问题,SO 可以使用更多!