SQL中的排名函数ROW_NUMBER() RANK() DENSE_RANK() NTILE() 有很强大的功能,首次见到还是在做推荐的时候(使用NTILE将按大小排序后的数据,运用一种合理的机制划分为N个组,这实际上类似于一种打分),在此我们将这四种排序函数做一一介绍。
我们使用的原始数据 order表:
(一)ROW_NUMBER: 按照提交时间的大小 给数据进行编号row_num
select ROW_NUMBER() OVER(order by [SubTime] desc) as row_num,* from [Order]
按提交时间编号后 再根据总价重新排序
select ROW_NUMBER() OVER(order by [SubTime] desc) as row_num,* from [Order] order by [TotalPrice] desc
利用row_number可以实现web程序的分页
with orderSection as
(
select ROW_NUMBER() OVER(order by [SubTime] desc) rownum,* from [Order]
)
select * from [orderSection] where rownum between 3 and 5 order by [SubTime] desc 选出提交时间位于3到5之间的
注意上面跟下面这个的区别!
with orderSection as
(
select ROW_NUMBER() OVER(order by [SubTime] desc) rownum,* from [Order]
)
select * from [orderSection] where rownum between 3 and 5 order by [TotalPrice] desc 选出提交时间3到5之间的,然后按照总价排序输出
(二)RANK:
select RANK() OVER(order by [UserId]) as rank,* from [Order]
(三)DENSE_RANK: 行号连续
select DENSE_RANK() OVER(order by [UserId]) as den_rank,* from [Order]
(四)NTILE:将有序分区中的行分发到指定数目的组中 共N组
select NTILE(4) OVER(order by [SubTime] desc) as ntile,* from [Order]
将排序后的六条数据,按照从大到小,合理的分配为四组。