How to iterate through table and modify entrys in an "if" statement with MySQL
What version of MySQL are you using? MySQL version 8 has Window Functions that support last_value(). 

Shy of using MySQL 8, you have two options,


Write a PROCEDURE that uses cursors in the database
Write a function that uses a cursor in a client side language.


My own preference, if I was to do this task in MySQL would be to write it outside of the server if that was reasonable (the data could be moved off-server), if not (we're talking about millions of rows) I would write a PROCEDURE