please help me fix query below to calculate running balance correctly.
What I need to do is:
- Calculate running balance (debit- credit) by account_no
- Reset the balance when account_no changes
- Reset the balance if transaction_date is in a new financial period AND account_type > 5
Query
SELECT
acc_account_transactions.id,
account_no,
account_type,
transaction_id,
DATE_FORMAT(acc_transactions.transaction_date,
'%d/%m/%Y') transaction_date,
debit_balance,
credit_balance,
IFNULL(acc_finacial_periods.id, - 1),
(@current_period_id:=IF(IFNULL(acc_finacial_periods.id, - 1) <> @current_period_id,
IFNULL(acc_finacial_periods.id, - 1),
@current_period_id)) current_period_id,
(@running_balance:=IF(@curr_account_no < account_no
OR (@current_period_id <> IFNULL(acc_finacial_periods.id, - 1)
AND account_type > 5),
0,
@running_balance)) prev_runnng_bal,
(@curr_account_no:=IF(@curr_account_no < account_no,
account_no,
@curr_account_no)) curr_account_no,
(@running_balance:=@running_balance + (acc_account_transactions.debit_balance - acc_account_transactions.credit_balance)) AS running_balance
FROM
(SELECT
@running_balance:=0,
@curr_account_no:=0,
@current_period_id:=- 1
) r,
acc_account_transactions
INNER JOIN
acc_transactions ON acc_transactions.id = acc_account_transactions.transaction_id
INNER JOIN
acc_accounts ON acc_accounts.id = acc_account_transactions.account_no
LEFT JOIN
acc_finacial_periods ON DATE_FORMAT(transaction_date, '%Y/%m/%d') >= DATE_FORMAT(startdate, '%Y/%m/%d')
AND DATE_FORMAT(transaction_date, '%Y/%m/%d') <= DATE_FORMAT(enddate, '%Y/%m/%d')
ORDER BY account_no , acc_account_transactions.id
What's wrong with it now?
- current_account_no variable has a wrong value, -it should be same as account_no column- hence, the running_balance result is also incorrect
Fiddle: here
Note: Database server info is below
Please don't close my question, I really need help :/
EDIT