前文中的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
结果集如下:
ID_ YEAR WEEK PRODUCT SALE RANK_SALE DENSE_RANK_SALE
---------- ---------- ---------- -------------------- ------------ ---------- ---------------
1 2000 1 product1 2003.10 1 1
301 2000 2 product1 2004.10 2 2
601 2000 3 product1 2005.10 3 3
901 2000 4 product1 2006.10 4 4
1201 2000 5 product1 2007.10 5 5
1501 2000 6 product1 2008.10 6 6
1801 2000 7 product1 2008.10 6 6
2101 2000 8 product1 2010.10 8 7
2401 2000 9 product1 2011.10 9 8
2701 2000 10 product1 2012.10 10 9
绿色数据为sale相同的数据,序号均为6
红色数据的时候,rank()函数返回8,跳过了7
而dense_rank()函数返回7,序号连续