Oracle 11g学习笔记–分析函数
示例表:
评级函数
rank()/dense_rank()
返回数据项在分组中的排名,前者在排名相等的情况下,会留下空位,后者不会
select emp_id, sum(amount),
rank() over (order by sum(amount) desc [{nulls last]|nulls first}]) as rank,
dense_rank() over (order by sum(amount) desc) as dense_rank
from all_sales
group by emp_id;
该句中的desc的含义就是降序,可换为asc进行升序排名;
[{nulls last]|nulls first}]指明了,将空结果排列在第一名,还是最排在最后一名;默认的情况下,系统会视空数据为最低,再根据升序或者降序选择显示位置;
cume_dist和percent_rank函数
cume_dist可以计算某个特定值相对于一组值中的位置;
percent_rank可计算某个值相对于一组值的百分比排名;
select
prd_type_id, sum(amount),
cume_dist() over (order by sum(amount) desc) as cume_dist,
percent_rank() over (order by sum(amount) desc) as percent_rank
from all_sales
where year = 2003
group by prd_type_id
order by sum(amount) desc;
从中我们便容易便可以看出两个函数的作用了
ntile(buket)函数
可以计算n分片的值,buket指定了分片的片数,记录将被分组为buket个片。
select prd_type_id, sum(amount),
ntile(3) over(order by sum(amount) desc) as ntile
from all_sales
where year = 2003
and amount is not null
group by prd_type_id
order by sum(amount) desc;
可以看出片规定了最低的名次,多出的名次均是第一;
row_number
row_number()从1开始,为每一条分组记录返回一个数字。
select
prd_type_id, sum(amount),
dense_rank() over (order by sum(amount) desc nulls last) as dense_rank,
row_number() over (order by sum(amount) desc nulls