本文意于用实例数据帮助理解SQL SERVER排名函数RANK,DENSE_RANK,NTILE,ROW_NUMBER。
html
?sql
1
2
3
4
5
|
create
table
test(
id
int
identity(1,1)
primary
key
,
testid
int
,
name
varchar
(100)
)
|
?ide
1
2
3
4
5
6
7
|
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,
'排名函数'
|
?函数
1
2
3
4
5
6
7
|
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 1
3 1 3 1 1 2
4 2 4 4 2 2
5 3 5 5 3 3
6 4 6 6 4 3
7 4 7 6 4 4spa
按testid升序排列为每个testid生成与之对应的一个序列数字,这些数字是从1开始由小到大的不间断数字。每一个序列数字是惟一的。code
按testid升序排列为每个testid生成与之对应的一个排名数字,这些数字是从1开始由小到大排序(可能间断)。相同的testid生成的排名数字也相同,可是下一排名数字不是由以前的排名数字加1计算出的,而是排名总数即行数。orm
按testid升序排列为每个testid生成与之对应的一个排名数字,这些数字是从1开始由小到大排序的不间断数字(可能重复)。相同的testid生成的排名数字也相同,可是下一排名数字是由以前的排名数字加1计算出,而不是排名总数或行数。htm
按testid升序排列并将全部testid平均分红4组(最后一组testid总数可能少于其它组),而后为每个testid生成与之对应的一个所属组编号。组编号是从1开始由小到大的不间断数字。排序
下面看一个带partition by的SQL语句来查看各个函数的使用:
1
2
3
4
5
6
7
|
select
id,testid,
name
,
ROW_NUMBER() over(partition
by
name
order
by
testid)
as
rownum,
RANK() over(partition
by
name
order
by
testid)
as
ranknum,
DENSE_RANK() over(partition
by
name
order
by
testid)
as
denseranknum,
Ntile(2) over (partition
by
name
order
by
testid)
as
ntilenum
from
test
order
by
name
|
运行结果:
id testid name rownum ranknum denseranknum ntilenum
1 1 LeeWhoee University 1 1 1 1
2 1 LeeWhoee University 2 1 1 1
3 1 LeeWhoee University 3 1 1 2
4 2 LeeWhoee University 4 4 2 2
5 3 排名函数 1 1 1 1
6 4 排名函数 2 2 2 1
7 4 排名函数 3 2 2 2
按name先进行数据分区,而后对每一区进行正常的ROW_NUMBER()计算。
按name先进行数据分区,而后对每一区进行正常的RANK()计算。
按name先进行数据分区,而后对每一区进行正常的DENSE_RANK()计算。
按name先进行数据分区,而后对每一区进行正常的Ntile()计算。
为了便于区分数据,在这里进行了NTILE(2)而不是NTILE(4)。