in reply to Re^2: How to add columns with new row name using perl from mysql query?
in thread How to add columns with new row name using perl from mysql query?
The hash won't preserve the sort order from the SQL so you have to retain that in an array which I have called @top
#!perl use DBI; use strict; my $DBH = get_dbh(); my $sql = 'SELECT queue_name,jobs_pend,jobs_run FROM queues ORDER BY jobs_run DESC'; my $sth = $DBH->prepare( $sql ); $sth->execute(); # input my %table = (); my $recno = 0; my @top = (); while (my ($name,$pend,$run) = $sth->fetchrow_array){ my $key = ($recno++ < 5) ? $name : 'other' ; $table{$key}{'pend'} += $pend; $table{$key}{'run'} += $run; push @top,$key unless ($top[-1] eq 'other'); } # output for my $key (@top){ my @col = ($key);# col[0] $col[1] = $table{$key}{'pend'}; $col[2] = $table{$key}{'run'}; printf "| %-25s | %3d | %3d |\n",@col; }
Update : you could just use an array without the hash
poj# input my @top = (); my $max = 5; my $recno = 0; while (my ($name,$pend,$run) = $sth->fetchrow_array){ my $ix = ($recno > $max) ? $max : $recno ; $top[$ix][0] = $name; $top[$ix][1] += $pend; $top[$ix][2] += $run; ++$recno; } $top[$max][0] = 'other'; # output for (@top){ printf "| %-25s | %3d | %3d |\n",@$_; }
|
|---|