我正在尝试编写一个查询(如果可能的话(来根据多个条件对 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 语句的条件返回排名,但看起来添加所需的分区会导致乘法,因为分组是必要的。 我可以为每列编写单独的查询,但如果可能的话,我想避免。
你想要这样的东西吗?
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;
这是我解释你可能想要什么的最佳猜测。