Instead of posting a bunch of code that doesn't work, please explain exactly what you want to do.
It would also help it you posted the structure of the table, some sample data, and a sample of the expected otuput.
I suspect the problem you are trying to solve is far simpler than you think.