I sometimes select and group into a temp table and then select, grouping again if nexessary) against the temp table. You can eliminate the inner loop often using this technique and it is usually more efficient. I am using the template toolkit for various tasks as well and have really found I have to mix it up. I have produced a lot of page from XML by preprocessing the db data and generating XML files that are actually used by the template to make things faster though the data is not actually "live" anymore.