简体   繁体   中英

Get top N from sorted group with SQL

Say I have table in this format:

在此处输入图像描述

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

在此处输入图像描述

Sum of channel B volume is 5150 which is larger than the 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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM