Skip to content
Advertisement

using ORDER BY in SQL for chunks of data

I want to know how I sort data in a SQL query but only in certain chunks. I’ll provide an example to make it easier.

In the above example, I want to do an ORDER BY height DESC, BUT only the tallest person of each rank gets ordered and everyone else in the same rank is right under that person ordered by height ASC. So the end result I want is:

So Tom is the tallest, so he goes up top, and automatically everyone everyone else in his rank goes underneath him but arranged ASC. John is tallest of the remaining so he and his group go next. What is the best query I can use to accomplish this?

Advertisement

Answer

First determine the champion of each rank

Determine the ranking for each rank by champion

Join back to both CTEs to get the ordering you specified. The rm.rank_height != h.height takes advantage of the fact that false comes before true when ordered to put the champion at the top of each rank grouping.

As pointed out by Gordon Linoff, this can be simplified to the following using only window functions:

Updated Working Fiddle.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement