【Oracle】【SQL】rownum, row_number() 和 rank()的區別

已知表結構如下:

SC表

sno

cno score
s001 c001 80
s001 c002 90
s002 c001 79
s002 c002 85
s003 c001 79
s003 c002 80

 

1. ROWNUM

1.1 rownum 是一個序列,是oracle數據庫從數據文件或緩存中讀取數據的順序, 如:

select * from sc where rownum = 1

結果返回SC表的第一行數據

sno

cno score
s001 c001 80

 

1.2 select rownum是在查詢結果中插入“僞列" 用於顯示查詢結果的序列,如:

select rownum, cno, score from sc where sno = 's001'

返回結果爲:

ronum

cno score
1 c001 80
2 c002 90

 

1.3 當rownum和order by 在同一個SQL出現時,數據庫將先對select結果插入rownum僞列在進行排序,如:

select rownum, cno, score from sc where sno = 's001' order by score DESC

返回結果爲:

rownum

cno score
2 c002 90
1 c001 80

 

1.4 在where語句中使用rownum時,不能使用> 或 between,如:

select * from sc where rownum > 2;

select * from sc where rownum between 1 and 1;

以上語句均返回空值

 

 

2. ROW_NUMBER()

2.1 跟rownum 類似,row_number() 也是在查詢結果中插入一個僞列,用以顯示每一行的序列,但是row_number()不可單獨使用,一般結合over(<window specification>)一起使用

如:

檢索SC表中每科成績前2名的同學:

select * from

(select sno, cno, score, row_number()over(partition by cno order by score DESC) rn

from sc)

where rn between 1 and 2

返回結果爲:

sno cno score RN
s001 c001 80 1
s002 c001 79 2
s001 c002 90 1
s002 c002 85 2

在上述語句中 row_number()over(partition by cno order by score DESC) 的含義是:

partition by cno: 以column cno 進行分組

order by score DESC: 在分組完成的基礎上,將每一組中的數據以column score 進行降序排列

row_number(): 在分組和排序完成的基礎上,在結果表中插入一行僞劣,用以顯示每一組的行序列。

 

 

3. RANK()

3.1 rank()跟row_number()的用法類似,通常跟over(partition by column A order by column B) 一起使用,區別是,row_number()返回結果不考慮列值相同的情況,而rank()返回列值相同的所有數據

如:

select * from

(select sno, cno, score, rank()over(partition by cno order by score DESC) rn

from sc)

where rn between 1 and 2

返回結果爲:

sno cno score RN
s001 c001 80 1
s002 c001 79 2
s003 c001 79 2
s001 c002 90 1
s002 c002 85 2

使用row_number()時RN的值按1,2,3,4 順序升序排列,不會重複

使用rank()時,對於值相同的行RN的值也相同,比如四行數據的第二行和第三行相同,那麼RN的值是:1,2,2,4

 

<完>

<歡迎糾錯/補充>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章