Hi Roopa,
Do not write select statement inside the loop it will degrade the performance, since for every loop a select statement will be executed. so better to write select statement outside the loop and did you implemented the logic you have mentioned , if not implement it and if you got stuck at any point let us know.
Thank you.