The way to program a page so that the output of the query is the way you want it, is first, do it yourself manually.
Notice exactly what you do and what decisions you make when placing each item. Write it down on paper each step of the way. Then go back and see how you can do that in whatever...