my $lastcountry = ''; my $totaldowntime = 0; while (my $row = $sth->fetch()) { (..., $country, $downtime, ...) = @$row; $totaldowntime += $downtime; if ($country ne $lastcountry) { # note this will be true first time thru the loop print $totaldowntime; $totaldowntime = 0; next_page(); # however you accomplish this in your setting }