zoukankan      html  css  js  c++  java
  • SQL 分页功能的实现

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

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

  • 相关阅读:
    android 加入关屏
    网址导航收集
    OpenStack 中文社区
    Truncate 删除数据
    c# 实体类生成工具
    .net 关系
    html中,播放 flash
    Axis2.0+WebService的使用
    xfire java web服务器引擎
    修复 google paly
  • 原文地址:https://www.cnblogs.com/aehyok/p/2800881.html
Copyright © 2011-2022 走看看