With your example, you can run
CREATE PROCEDURE procedure_name()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE _accoujntno INTEGER DEFAULT 0;
DECLARE _uacn varchar(191) DEFAULT "";
DEClARE curaccount
CURSOR FOR
Select account_no ,user_account_number FROM TBL1 WHERE length(user_account_number)-length(replace(user_account_number,'-',''))+1 = 2 order by user_account_number;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
CREATE TEMPORARY TABLE credits(
user_account_number VARCHAR(191),
`Debit_Before_Period` DECIMAL(20,2),
`Credit_Before_Period` DECIMAL(20,2),
`Debit_In_Period` DECIMAL(20,2),
`Credit_In_Period` DECIMAL(20,2)
);
OPEN curaccount;
getaccount: LOOP
FETCH curaccount INTO _accoujntno,_uacn;
IF finished = 1 THEN
LEAVE getaccount;
END IF;
INSERT INTO credits SELECT _uacn ,SUM(`Debit Before Period`),SUM(`Credit Before Period`) ,SUM(`Debit In Period`) ,SUM(`Credit In Period`)
FROM TBL1
WHERE LEFT(user_account_number,7) = _uacn AND account_no <> _accoujntno;
END LOOP getaccount;
CLOSE curaccount;
SELECT * FROM credits;
END
The resulting temporary table credits you can use to run further analysis
simply add the procedure and CALL procedure_name()
In a query tab in phmyadmin wor mysql Workbench you need to add DELIMITER to the procedure, but that doesn't work in dbfiddle
example
It is like in the comment
CREATE PROCEDURE procedure_name()
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE _accoujntno INTEGER DEFAULT 0;
DECLARE _uacn varchar(191) DEFAULT "";
DEClARE curaccount
CURSOR FOR
Select account_no ,user_account_number FROM TBL1 WHERE length(user_account_number)-length(replace(user_account_number,'-',''))+1 = 1 order by user_account_number;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
CREATE TEMPORARY TABLE credits(
user_account_number VARCHAR(191),
`Debit_Before_Period` DECIMAL(20,2),
`Credit_Before_Period` DECIMAL(20,2),
`Debit_In_Period` DECIMAL(20,2),
`Credit_In_Period` DECIMAL(20,2)
);
OPEN curaccount;
getaccount: LOOP
FETCH curaccount INTO _accoujntno,_uacn;
IF finished = 1 THEN
LEAVE getaccount;
END IF;
INSERT INTO credits SELECT _uacn ,SUM(`Debit Before Period`),SUM(`Credit Before Period`) ,SUM(`Debit In Period`) ,SUM(`Credit In Period`)
FROM TBL1
WHERE LEFT(user_account_number,3) = _uacn;
END LOOP getaccount;
CLOSE curaccount;
SELECT * FROM credits;
END
new example