I don't think I have a clear idea of your database structure. Is this all in one table? If so, can you give a slightly better idea what this table looks like?
Usually I try to put as much of the logic in my query as possible. Can you conceive of a way to do most of this work in your SQL?