Hi,
Instead of writing the sort statement inside the loop, in smartforms for a table you have the option to sort and perform calculations. If you go tot the calculations tab in the table you have the options to perform various calculations based on different conditions.
Regards
Ansari