Home > Enterprise >  Get top N from sorted group with SQL
Get top N from sorted group with SQL

Time:06-07

Say I have table in this format:

enter image description here

I want to get top 2 from each channel but the channel order is sorted by sum of volume first. Expected result is:

enter image description here

Sum of channel B is 5100 with is larger than sum of channel A with 3500.

I saw some questions that user ROW_NUMBER() but it only work to get top N from each category with no order in category. How do I approach this problem?

CodePudding user response:

You can use ROW_NUMBER() with SUM analytical functions in ORDER BY clause -

SELECT channel, category, volume
  FROM (SELECT ROW_NUMBER() OVER(PARTITION BY channel ORDER BY volume DESC) RN,
               SUM(volume) OVER(PARTITION BY channel) tot_volume
               channel, category, volume
          FROM (SELECT channel, category, SUM(volume) volume
                  FROM your_table
                 GROUP BY channel, category
               ) t
        ) tmp
 WHERE RN <= 2
 ORDER BY tot_volume DESC, volume DESC;
  • Related