This sounds like you're implementing a bit of a data cube (think OLAP). You may want to look and see what there is for calculating cubes on data via Class::DBI. If you were going to do this it'd help if you were aware of the space you're working with.