1.首先介紹ROW_NUMBER() OVER的基本用法
2.看一下實例數據
初始化數據
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)
數據結果顯示
根據部門分組(deptid),顯示每個部門的工資(salary)等級
這是想要得到的結果第二列根據部門進行分組,第三列工資由高到低,rank進行部門內部的排列
3.簡單分頁實現
SELECT Row_Number() OVER (ORDER BY salary desc) rank,* FROM employee
根據上面1,2兩點我們可以看出這個SQL只是按照工資降序排序後,並沒有通過PARTITION BY COLUMN進行分區(分組),然後通過row_number()從1開始,為每一條分組記錄返回一個數字。結果如下
將上面SQL返回的結果集當作一個數據表
(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
當然我們第二頁這裡只有4條記錄。
分頁就這樣實現了,對於多表查詢進行分頁也是同樣的道理。