this is a very complex idea. You would probably need to run several arrays at the same time, to store values and counts and to give you chance of getting the result that you want.
I don't think that I would want to tackle this anytime soon. A stored procedure would probably give you much nicer results.
Sorry I can't be or more help.