SQL解析函数:排名在多个分区
问题描述:
有朋友问与下面的查询服务(见其他说明图像):SQL解析函数:排名在多个分区
“我们需要生成一个基于销售项目的数量销售排名,按产品计算,换句话说,对于给定的产品,销售数量最多的一年将排在第1位,下一个销售数量的年份将排在第2位,依此类推“
我给他发了下面的SQL,不过他说所有排都回来了,排名为1
Select product, year, num_of_items_sold
RANK() OVER (PARTITION BY product, year ORDER BY num_of_items_sold) as sales_rank
from prod_sales
我错过了什么吗?谢谢。
答
考虑的问题,它可能看起来奇怪,year
不需要在窗口的功能。所有它关心的是product
和物品的销售数量:
select product, year, num_of_items_sold
rank() over (partition by product
order by num_of_items_sold desc
) as sales_rank
还要注意为order by
的降序排序。
+0
戈登,你是对的。鉴于问题的语言,我设法混淆了自己。如果您知道某个源提供了由多个分区(多于一个字段)分割的rank函数的简洁示例,请您直接向我介绍。非常感激。 – JohnGagliano
+0
@JohnGagliano。 。 。我认为你只需要练习。窗口函数影响*整个*行,'year'只是行中的另一列。 –
使用'PARTITION BY product ORDER BY num_of_items_sold desc' –
您使用的数据库是?甲骨文? – SandPiper
postgres。谢谢 – JohnGagliano