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


前言


本文意於用實例數據幫助理解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, '排名函數'

用一個SQL語句來查看各個函數的使用:

 

?函數

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

ROW_NUMBER() over( order by testid)

按testid升序排列爲每個testid生成與之對應的一個序列數字,這些數字是從1開始由小到大的不間斷數字。每一個序列數字是惟一的。code

RANK() over(order by testid)

按testid升序排列爲每個testid生成與之對應的一個排名數字,這些數字是從1開始由小到大排序(可能間斷)。相同的testid生成的排名數字也相同,可是下一排名數字不是由以前的排名數字加1計算出的,而是排名總數即行數。orm

DENSE_RANK() over(order by testid)

按testid升序排列爲每個testid生成與之對應的一個排名數字,這些數字是從1開始由小到大排序的不間斷數字(可能重複)。相同的testid生成的排名數字也相同,可是下一排名數字是由以前的排名數字加1計算出,而不是排名總數或行數。htm

Ntile(4) over ( order by testid)

按testid升序排列並將全部testid平均分紅4組(最後一組testid總數可能少於其它組),而後爲每個testid生成與之對應的一個所屬組編號。組編號是從1開始由小到大的不間斷數字。排序

partition by

下面看一個帶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

ROW_NUMBER() over(partition by name order by testid)

按name先進行數據分區,而後對每一區進行正常的ROW_NUMBER()計算。

RANK() over(partition by name order by testid)

按name先進行數據分區,而後對每一區進行正常的RANK()計算。

DENSE_RANK() over(partition by name order by testid)

按name先進行數據分區,而後對每一區進行正常的DENSE_RANK()計算。

Ntile(2) over (partition by name order by testid)

按name先進行數據分區,而後對每一區進行正常的Ntile()計算。

爲了便於區分數據,在這裏進行了NTILE(2)而不是NTILE(4)。

相關文章
相關標籤/搜索