I am developing a accounting software. Want to maintain day wise opening and closing balance. Opening balance for a date is closing balance of previous date. Whenever a transaction for a specific date is added / updated opening and closing balance of that date and all dates after that should be updated into table. Table structure I created is
CREATE TABLE IF NOT EXISTS `account_ledger_day_balances` (
`acdb_id` int(11) NOT NULL AUTO_INCREMENT,
`account_ledger_id` int(11) NOT NULL,
`transaction_date` date NOT NULL,
`company_id` int(11) NOT NULL,
`financial_year` int(11) NOT NULL,
`day_amount` float NOT NULL,
`opening_balance` float NOT NULL,
`closing_balance` float GENERATED ALWAYS AS ((`day_amount` + `opening_balance`)) VIRTUAL NOT NULL,
PRIMARY KEY (`acdb_id`),
UNIQUE KEY `unique` (`account_ledger_id`,`transaction_date`,`company_id`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
COMMIT;
INSERT INTO `account_ledger_day_balances` (`acdb_id`, `account_ledger_id`, `transaction_date`, `company_id`, `financial_year`, `day_amount`, `opening_balance`) VALUES
(NULL, '1012', '2020-06-20', '1', '0', '-164670', '0'),
(NULL, '1012', '2020-06-30', '1', '0', '-53957.6', '0'),
(NULL, '1012', '2020-07-17', '1', '0', '-21000', '0'),
(NULL, '1012', '2020-09-01', '1', '0', '-1667.7', '0'),
(NULL, '1012', '2020-09-09', '1', '0', '-47640', '0'),
(NULL, '1012', '2020-09-10', '1', '0', '-36912', '0'),
(NULL, '1012', '2020-09-16', '1', '0', '-9600', '0'),
(NULL, '1012', '2020-09-21', '1', '0', '-25680', '0'),
(NULL, '1012', '2020-09-28', '1', '0', '-6000', '0'),
(NULL, '1012', '2020-10-14', '1', '0', '-6930', '0'),
(NULL, '1012', '2020-10-15', '1', '0', '-7800', '0'),
(NULL, '1012', '2020-10-21', '1', '0', '-7800', '0'),
(NULL, '1012', '2020-10-22', '1', '0', '-12000', '0'),
(NULL, '1012', '2020-11-20', '1', '0', '-540', '0')
After every transaction I update day_amount into this table but not able to update opening balance of all dates of transaction_date and after that.
Tried following query and it updates but not taking closing balance.
UPDATE `account_ledger_day_balances` SET opening_balance = (SELECT closing_balance1 FROM
(SELECT (day_amount + opening_balance) as closing_balance1, account_ledger_id, transaction_date FROM account_ledger_day_balances) as prev_day
WHERE prev_day.account_ledger_id = account_ledger_day_balances.account_ledger_id AND
prev_day.transaction_date < account_ledger_day_balances.transaction_date
ORDER BY prev_day.transaction_date DESC LIMIT 0,1) WHERE `account_ledger_id` = 1012
Output what I want is as below
Date Day Amount Opening Balance Closing Balance
2020-06-20 -164670 0 -164670
2020-06-30 -53957.6 -164670 -2,18,627.6
2020-07-17 21000 -2,18,627.6 -1,97,627.6