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