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.