in reply to Logic problem on loops

Using one column for each month makes it rather hard to get the database to some of this work for you. If instead of the "f1".."f12", etc., columns you had a "month" column and single columns for "f", "m", "rf", and "rm", you could do the month selection and trimester rollups via a query. A bit of reading on relational database "normal forms" and their benefits might pay off for you.

I'm suspicious of the DISTINCT in that second SELECT. Are you really sure you're gettin back the data you want?

Without knowing more about the data, it's hard to know whether you have a problem tripping the month tests multiple times. I suggest adding

if ($month eq "1") #January, obviously { >>> $message .= "<!-- January -->\n";
and so on for the other months. This will tell you whether you're accidentally tripping those tests multiple times, and clobbering counters.