input:

output what i want is:

input:

output what i want is:

Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Sep 29, 2022, 8:23 AM EDT
Refer this optimized query
with cte as ( SELECT *, row_number() over (partition by accountno order by trandate desc) as rn FROM test ) select accountno, trandate, amount, paidamount, balance, coalesce(balance + (select sum(balance) from cte a where a,rn > b.rn and a.accountno = b.accountno ), 0) as previous_balance from cte b order by b.accountno, b.trandateAmit MohantyRank #112 · 20K reputationPosted Sep 29, 2022, 5:42 AM EDT
Try this
SELECT `Accountno` ,`Trandate` ,`Amount` ,`Paidamount` ,`Balance` , (SELECT SUM(`Balance`) FROM `YourTableName` WHERE `Trandate` <= T1.`Trandate` AND `Accountno` = T1.`Accountno`) INTO `Prevbalance` FROM `YourTableName` T1