Why is there nothing in your second query ("SELECT DISTINCT " .$fa...) to specify which month you're working on? Do you get the exact same too-big numbers for all trimesters? I would expect this to happen, because it looks like you are doing

while (@rown = $sthn->fetchrow_array())

over the same set of rows in each of the twelve iterations through the months.

So, does the DB schema provide any information to identify which month applies to each of the various rows containing "first" and "second" "predicted" and "realized" values? If so, work that into the query. If not, you can't do the trimester tabulation at all, no matter how good your Perl code is.

If/when you solve that problem, then think of the tabulation this way (it will make the code shorter and easier):

foreach $filiais (@filiais){ # print an html header (you don't need $cnt2 for this) $tf = $trf = $tm = $trm = 0; # set accumulators to 0 foreach $month (1 .. 12) { # query DB for rows of 4 values _for_this_month_ while (@rown = $sthn->fetchrow_array()) { ($fa,$rfa,$ma,$rma) = @rown; $tf += $fa; # and likewise for the other three accumulators } if ( $month % 3 == 0 ) { # true for months 3,6,9,12 ListTrimestre( $tf,$trf,$tm,$trm,$month/3 ); $tf = $trf = $tm = $trm = 0; # reset accumulators to 0 } } }

In reply to Re: Logic problem on loops by graff
in thread Logic problem on loops by DaWolf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.