赞
踩
简述:根据窗口分区中行的顺序,为每一行返回一个唯一的顺序号(从1开始)。
注意:不能用作于学生成绩的排名,一般多用于分页查询,比如求TopN。
按照订单金额排序获取序号
select
order_amount,
ROW_NUMBER() OVER(order by order_amount desc) rn
from yp_dwb.dwb_order_detail;
select *
from (
select order_amount,
ROW_NUMBER() OVER(order by order_amount desc) rn
from yp_dwb.dwb_order_detail
)
where rn <= 10;
获取每个店铺金额排行Top10的订单
select *
from (
select
order_amount,
store_id,
row_number() over (partition by store_id order by order_amount desc) rn
from yp_dwb.dwb_order_detail
)
where rn <= 10;
描述:返回值在一组值中的排名。当存在相同金额的订单时,ROW_NUMBER()会一次进行排序,每行数据的序号不相通,而RANK()则不一样,出现相同的金额时,他们的排名是一样的。
获取金额rank排名Top10订单
select *
from (
select order_amount,
row_number() over (order by order_amount desc) rn,
rank() over(order by order_amount desc) rn_rank
from yp_dwb.dwb_order_detail
)
where rn_rank <= 10;
获取各店铺rank排名Top10订单
select *
from (
select order_amount,
store_id,
row_number() over (partition by store_id order by order_amount desc) rn,
rank() over(partition by store_id order by order_amount desc) rn_rank
from yp_dwb.dwb_order_detail
)
where rn_rank <= 10;
返回值在一组值中的排名。这与rank()相似,不同之处在于排名的连续性,DENSE_RANK()排名是连续的,RANK()是跳跃的排名,所以一般情况下用的排名函数就是RANK()。
select *
from (
select order_amount,
row_number() over (order by order_amount desc) rn,
rank() over(order by order_amount desc) rn_rank,
dense_rank() over (order by order_amount desc) rn_dense_rank
from yp_dwb.dwb_order_detail
)
where rn_dense_rank <= 10;
获取各店铺金额dense——rank排名Top10订单
select *
from (
select order_amount,
store_id,
row_number() over (partition by store_id order by order_amount desc) rn,
rank() over(partition by store_id order by order_amount desc) rn_rank,
dense_rank() over (partition by store_id order by order_amount desc) rn_dense_rank
from yp_dwb.dwb_order_detail
)
where rn <= 10;
NTILE()函数它把有序的数据集合平均分配到指定的数量(num)个组中,如果不能平均分配,则优先分配较小编号的组,并且各个组中能放的行数最多的相差1。各个组有编号,编号从1开始,就像我们说的‘分区’一样,分为几个区,一个区会有多少个
每个组行数最多相差1的含义:
获取金额NTILE500的Top10订单
select *
from (
select order_amount,
row_number() over (order by order_amount desc) rn,
rank() over(order by order_amount desc) rn_rank,
dense_rank() over (order by order_amount desc) rn_dense_rank,
ntile(500) over(order by order_amount desc) rn_ntile
from yp_dwb.dwb_order_detail
)
where rn_ntile <=10;
获取各店铺金额ntile500的Top10订单
select *
from(
select order_amount,
store_id,
row_number() over (partition by store_id order by order_amount desc) rn,
rank() over(partition by store_id order by order_amount desc) rn_rank,
dense_rank() over (partition by store_id order by order_amount desc) rn_dense_rank,
ntile(500) over(partition by store_id order by order_amount desc) rn_ntile
from yp_dwb.dwb_order_detail
)
where rn_ntile <= 10;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。