Skip to content
Advertisement

Order by descending aggregation within window function in PostgreSQL

I have a dataset that features duplicate values of the the primary variable, something like the following:

I have achived this by using the following code

However, my desired output needs to be ordered such that counts is descending yet col1 remains partitioned, so that I can see, for example, which value from col1 has the highest number of counts. Like this…

I have tried various iterations of the final ORDER BY clause but just can’t quite produce the output I need. Guidance appreciated.

Advertisement

Answer

You can use window functions in the order by. I think you just want:

This assumes that the count is the maximum value of row_numb(). So you can also express this as:

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