I'm not understanding what you are trying to do. Why not use SQL? If you do not want to use a fancy SQL statement in your perl, why not create a view, and just query that instead. BTW, another way to do it, is with UNION ALL and subqueries. That is (simplified):
select group, (select member where order = 1) union all
select group, (select member where order = 2) union all
For only 5 of each, this is a pretty simple way that should work in any database. It can be done without UNION ALL by using sub-queries for your tables, and so on.