http://qs321.pair.com?node_id=390806


in reply to Re^2: Finer points of Class::DBI
in thread Finer points of Class::DBI

Yeah, some more details on the db architecture would be very useful since this seems like more of a query issue than anything else.

While I can envision a number of ways that an area would have a 1..n relationship with the statistics, I'm just going to have to guess at the field layout (note, I'm not even getting into normalisation):

--------------------  --------------------
| Areas            |  | Stats            |
--------------------  --------------------
| PersonId         |  | PersonId         |
| Person           |  | Person           |
| Group            |  | Stat             |
--------------------  | MonthKey         |
                      --------------------

Assuming that your setup looks anything like this, then there are several ways to query this table for an ordered list of stats.

If you wanted everything ordered by date (so no rollup) it would be:

SELECT monthKey, group, person, stat FROM areas a, stats s WHERE a.personId=s.personId ORDER BY monthKey, group, person, stat ;

If you wanted to get a date range it would be:

SELECT monthKey, group, person, stat FROM areas a, stats s WHERE a.personId=s.personId AND s.monthKey > 200401 AND s.monthKey < 200406 ORDER BY monthKey, group, person, stat ;

And so on.

The output from this query would be quite easy to work with in Perl because you can run through the output without worrying about order:

my $sth = $dbh->prepare($query); $sth->execute(); my $current_month; my $current_group; my $current_person; while (my $rv = $sth->fetchrow_arrayref()); if ($rv[0] ne $current_monthkey) { # print out new month header $current_month = $rv[0]; undef $current_group; undef $current_person; } if ($rv[1] ne $current_group) { # print out new group header $current_group = $rv[0]; undef $current_person; } if ($rv[2] ne $current_person) { # print out new person header $current_person = $rv[1]; } # print out stat } $sth->finish(); $dbh->disconnect();

Hope that helps -- it was a bit of a speculative jump based on the available information, but dbs are designed for querying, sorting, and ordering in clever ways that require you to be a true programming god to reproduce in Perl with anything like comparable performance.