首页 > 代码库 > 使用分析函数

使用分析函数

--原始数据
select prd_type_id,
sum(amount)
from ALL_SALES
where year = 2003
and amount is not null
group by prd_type_id
order by prd_type_id;

--可以计算数据项在分组中的排名
select prd_type_id,
sum(amount),
row_number()over(order by sum(amount) desc) row_number,--无并列,根据sum(amount)倒序排名
rank()over(order by sum(amount) desc) rank, --并列不连续
dense_rank()over(order by sum(amount) desc) dense_rank --并列连续
from ALL_SALES
where year = 2003
and amount is not null
group by prd_type_id
order by prd_type_id;

--在递减排序中将空值指定为最高的排名,在递增排序指定为最低排名
select prd_type_id,
sum(amount),
row_number()over(order by sum(amount) desc) row_number,
rank()over(order by sum(amount) desc) rank,
dense_rank()over(order by sum(amount) desc) dense_rank
from ALL_SALES
where year = 2003
group by prd_type_id
order by prd_type_id;

--使用nulls last将空值指定为最低
select prd_type_id,
sum(amount),
row_number()over(order by sum(amount) desc nulls last) row_number,
rank()over(order by sum(amount) desc nulls last) rank,
dense_rank()over(order by sum(amount) desc nulls last) dense_rank
from ALL_SALES
where year = 2003
group by prd_type_id
order by prd_type_id;

--分析函数结合partition by字句
select prd_type_id,
month,
sum(amount),
rank()over(partition by month order by sum(amount) desc) rank --并列不连续,根据month分组之后sum(amount)倒序排名
from ALL_SALES
where year = 2003
and amount is not null
group by prd_type_id, month
order by prd_type_id, month;

--rollup
select prd_type_id,
sum(amount),
rank()over(order by sum(amount) desc) rank
from ALL_SALES
where year = 2003
group by rollup(prd_type_id)
order by prd_type_id;

--cube
select prd_type_id,emp_id,
sum(amount),
rank()over(order by sum(amount) desc) rank
from ALL_SALES
where year = 2003
group by cube(prd_type_id,emp_id)
order by prd_type_id,emp_id;

--grouping sets
select prd_type_id,emp_id,
sum(amount),
rank()over(order by sum(amount) desc) rank
from ALL_SALES
where year = 2003
group by grouping sets(prd_type_id,emp_id)
order by prd_type_id,emp_id;

--cume_dist
--percent_rank
select prd_type_id,
sum(amount),
cume_dist()over(order by sum(amount) desc) cume_dist,
percent_rank()over(order by sum(amount) desc) percent_rank
from ALL_SALES
where year = 2003
group by prd_type_id
order by prd_type_id;

使用分析函数