前文中的First_value、Last_value和Nth_value用于提取指定的行
某些时候,我们需要对分区中的数据进行排序,并得到序号,
这样,rank()和dense_rank()函数就用上了。
rank() over(partition by ... order by ...)
dense_rank() over(partition by ... order by ...)
rank和dense_rank不支持开窗语句
如果出现相同的行,那么rank函数将跳过这些行,形成新的排名
而dense_rank则形成连续的排名
示例:
第一步,创建一个具有相同sale的数据行
update sales_fact set sale='2008.10' where id_=1801;
SQL如下:
select id_,
year,week,product,
sale,
rank() over (
partition by product,region,country,year
order by sale
) rank_sale,
dense_rank() over (
partition by product,region,country,year
order by sale
) dense_rank_sale
from sales_fact
where product='product1' and country='country1' and region='region1'
order by product,country,year,week
结果集如下: