Rewriting calculation of results by using a loop + add comments of the sql query