SQL SERVER排名函数RANK,DENSE_RANK,NTILE,ROW_NUMBER

本文详细介绍了SQL SERVER中的四个排名函数:ROW_NUMBER、RANK、DENSE_RANK和NTILE,通过实例展示了它们在不同场景下的使用,包括如何对数据进行排序、分组以及生成排名或分组编号。

SQL SERVER排名函数RANK,DENSE_RANK,NTILE,ROW_NUMBER


前言


本文意于用实例数据帮助理解SQL SERVER排名函数RANK,DENSE_RANK,NTILE,ROW_NUMBER。


准备工作


创建测试表:

create table test(
id int identity(1,1) primary key,
testid int,
name varchar(100)
)


插入测试数据:

insert into test(testid,name)select 1,'LeeWhoee University'
insert into test(testid,name)select 1,'LeeWhoee University'
insert into test(testid,name)select 1,'LeeWhoee University'
insert into test(testid,name)select 2,'LeeWhoee University'
insert into test(testid,name)select 3,'排名函数'
insert into test(testid,name)select 4,'排名函数'
insert into test(testid,name)select 4,'排名函数'


用一个SQL语句来查看各个函数的使用:

select id,testid,
ROW_NUMBER() over( order by testid) as rownum,
RANK() over(order by testid) as ranknum,
DENSE_RANK() over(order by testid) as denseranknum,
Ntile(4) over ( order by testid) as ntilenum
from test
order by testid


下面是运行结果:

id    testid    rownum    ranknum    denseranknum    ntilenum
1    1            1                 1                   1                             1
2    1            2                 1                   1               &nbs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值