>데이터 베이스 >MySQL 튜토리얼 >SQL2005利用ROW_NUMBER() OVER实现分页功能

SQL2005利用ROW_NUMBER() OVER实现分页功能

WBOY
WBOY원래의
2016-06-07 17:56:25859검색

SQL2005利用ROW_NUMBER() OVER实现分页功能,需要的朋友可以参考下

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条记录。

分页就这样实现了,对于多表查询进行分页也是同样的道理。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.