[eluser]tonanbarbarian[/eluser]
You can actually do all of this in the query
It is what is commonly refered to as a cross-tab query
I have done them heaps of time.
Unfortunately it would take me too long to explain, and I doubt it would explain it well
I recommend googling cross tab query mysql and see what it comes it with
It should show you how to build a query that gives you all of your data exactly as you need it in one monolithic query
And despite the site of the query string it will find the data pretty quickly for you