如何对数据组进行排名?

问题描述

给出以下内容,并负责按每个组中的SUM(卷)对原始数据进行排名:

group_id    volume
1           2
1           3
2           5
3           1
3           3

如何获取以下内容

group_id    volume  group_volume    rank
1           2       5               1
1           3       5               1
2           5       5               2
3           1       4               3
3           3       4               3

我可以很容易地获得group_volume,但是我在如何打破排名关系上却苦苦挣扎,而又没有在单独的子查询中加入+排名来分组并加入。

SELECT *,SUM(volume) OVER (PARTITION BY group_id) AS grouped_volume,... AS rank
FROM groups

解决方法

为此使用两个级别的窗口功能:

select g.*,dense_rank() over (order by group_volume desc,group_id) as rank
from (select g.*,sum(volume) over (partition by group_id) as group_volume
      from groups g
     ) g;

不需要JOIN

,

使用CTE和Dense_rank

WITH CTE1 AS (SELECT group_id,volume,sum(volume) over(partition by group_id) group_volume
from table1)
SELECT A.*,dense_rank() over( order by  group_id,group_volume) rank FROM CTE1 A;