Presto SQL-对多个列的多个条件进行排名

时间:2018-08-29 23:13:01

标签: sql presto

我正在尝试编写一个查询(如果可能)以根据多个条件对ID进行排名。

我的桌子是这样的:

id     group    subgroup  value
1      A        Q         12
2      A        Z         10
3      B        Z         14
4      A        Z         20
5      B        W         20

我尝试了以下查询:

SELECT id,
       CASE WHEN group = 'A' THEN ROW_NUMBER() OVER (PARTITION BY group ORDER BY SUM(value) DESC) AS rank_group
       CASE WHEN group = 'A' AND subgroup = 'Z' THEN ROW_NUMBER() OVER (PARTITION BY group, subgroup ORDER BY SUM(value) DESC) AS rank_subgroup
FROM table
GROUP BY group, subgroup

但最终却是这样的:

id     rank_group    rank_subgroup
1      1             1
1      2             2

我想获取每个不同的id并根据case语句的条件返回排名,但是看起来像添加所需的分区会导致乘法,因为group by是必要的。我可以为每一列编写单独的查询,但如果可能的话,我想避免。

1 个答案:

答案 0 :(得分:0)

您想要这样的东西吗?

select t.*,
       dense_rank() over (order by sumg, group),
       dense_rank() over (partition by group order by sumsg, subg),
from (select t.*,
             sum(value) over (partition by group) as sumg,
             sum(value) over (partition by group, subgroup) as sumsg
      from t
     ) t;

这是我解释您可能想要的最好的猜测。