简体   繁体   English

使用 SQL 从排序组中获取前 N 个

[英]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 .我想从每个频道中获得前 2 名,但频道顺序是按音量总和排序的 Expected result is:预期结果是:

在此处输入图像描述

Sum of channel B volume is 5150 which is larger than the sum of channel A with 3500.通道 B 的总和为 5150,大于通道 A 与 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.我看到了用户 ROW_NUMBER() 的一些问题,但它只能从每个类别中获得前 N 个,而类别中没有顺序。 How do I approach this problem?我该如何解决这个问题?

You can use ROW_NUMBER() with SUM analytical functions in ORDER BY clause -您可以在 ORDER BY 子句中将 ROW_NUMBER() 与 SUM 分析函数一起使用 -

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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