Skip to content
Advertisement

Sum rows not in the top x rows of a group in the table into an “other” row?

If I have a table like the following which is the number of records with a given label grouped by a certain category (in this case Male, Female),

How would I transform it into a table that keeps the top x (e.g. 5 records) for each category, when the rows are sorted by number descending, and sums the remaining rows for that category into an “other” row? The desired output (assuming we are keeping the top 5) is below:

Advertisement

Answer

You can use window functions and aggregation:

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