Can i suggest the following depending on the Database you are using?

If you are using Access then use a Crosstab query
If you are using SQL Server then use a Cursor to go thru your results.

Hope this helps