1.首先介紹ROW_NUMBER() OVER的基本用法
2.看一下實(shí)例數(shù)據(jù)
初始化數(shù)據(jù)
create table employee (empid int ,deptid int ,salary decimal(10,2))
insert into employee values(1,10,5500.00)
insert into employee values(2,10,4500.00)
insert into employee values(3,20,1900.00)
insert into employee values(4,20,4800.00)
insert into employee values(5,40,6500.00)
insert into employee values(6,40,14500.00)
insert into employee values(7,40,44500.00)
insert into employee values(8,50,6500.00)
insert into employee values(9,50,7500.00)
數(shù)據(jù)結(jié)果顯示
根據(jù)部門分組(deptid),顯示每個(gè)部門的工資(salary)等級(jí)
這是想要得到的結(jié)果第二列根據(jù)部門進(jìn)行分組,第三列工資由高到低,rank進(jìn)行部門內(nèi)部的排列
3.簡單分頁實(shí)現(xiàn)
SELECT Row_Number() OVER (ORDER BY salary desc) rank,* FROM employee
根據(jù)上面1,2兩點(diǎn)我們可以看出這個(gè)SQL只是按照工資降序排序后,并沒有通過PARTITION BY COLUMN進(jìn)行分區(qū)(分組),然后通過row_number()從1開始,為每一條分組記錄返回一個(gè)數(shù)字。結(jié)果如下
將上面SQL返回的結(jié)果集當(dāng)作一個(gè)數(shù)據(jù)表
(SELECT Row_Number() OVER (ORDER BY salary desc) rank,* FROM employee)as NewTable
假如我們每頁5條記錄,
那么第一頁顯示select * from (SELECT Row_Number() OVER (ORDER BY salary desc) rank,* FROM employee ) as NewTable where rank between 1 and 5
第二頁為select * from (SELECT Row_Number() OVER (ORDER BY salary desc) rank,* FROM employee ) as NewTable where rank between 6 and 10
當(dāng)然我們第二頁這里只有4條記錄。
分頁就這樣實(shí)現(xiàn)了,對(duì)于多表查詢進(jìn)行分頁也是同樣的道理。
標(biāo)簽:公主嶺 臺(tái)灣 商洛 咸寧 ???/a> 西藏 日喀則 寶雞
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《SQL2005利用ROW_NUMBER() OVER實(shí)現(xiàn)分頁功能》,本文關(guān)鍵詞 SQL2005,利用,ROW,NUMBER,OVER,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。