The exact logic is there in standard report MB5B.
There are many calculation for many table in this report.
You can't get the opening balance and closing balance in one table.
If you are an ABAP, then you should read the logic of program RM07MLBD.
Then you can make the Z report as per your requirement.