zoukankan      html  css  js  c++  java
  • 分区函数Partition By的与row_number()的用法以及与排序rank()的用法详解(获取分组(分区)中前几条记录)(转)

    转载地址:http://www.cnblogs.com/linJie1930906722/p/6036053.html

    partition by关键字是分析性函数的一部分,它和聚合函数不同的地方在于它能返回一个分组中的多条记录,而聚合函数一般只有一条反映统计值的记录,partition by用于给结果集分组,如果没有指定那么它把整个结果集作为一个分组,分区函数一般与排名函数一起使用。

    准备测试数据:

    复制代码
    create table Student  --学生成绩表
    (
     id int,  --主键
     Grade int, --班级
     Score int --分数
    )
    go
    
    insert into Student values(1,1,88)
    insert into Student values(2,1,66)
    insert into Student values(3,1,75)
    insert into Student values(4,2,30)
    insert into Student values(5,2,70)
    insert into Student values(6,2,80)
    insert into Student values(7,2,60)
    insert into Student values(8,3,90)
    insert into Student values(9,3,70)
    insert into Student values(10,3,80)
    insert into Student values(11,3,80)
    复制代码

    一、分区函数Partition By的与row_number()的用法

    1、不分班按学生成绩排名

    select *,row_number() over(order by Score desc) as Sequence from Student

    执行结果:

    2、分班后按学生成绩排名

    select *,row_number() over(partition by Grade order by Score desc) as Sequence from Student

    执行结果:

    3、获取每个班的前1(几)名

    select * from
    (
    select *,row_number() over(partition by Grade order by Score desc) as Sequence from Student
    )T where T.Sequence<=1

    执行结果:

    二、分区函数Partition By与排序rank()的用法

    1、分班后按学生成绩排名 该语句是对分数相同的记录进行了同一排名,例如:两个80分的并列第2名,第4名就没有了

    select *,rank() over(partition by Grade order by Score desc) as Sequence from Student

    执行结果:

    2、获取每个班的前2(几)名 该语句是对分数相同的记录进行了同一排名,例如:两个80分的并列第2名,第4名就没有了

      简单来说就是类似于row_number,不同之处在于,它会对order by 的字段进行处理,如果这个字段值相同,那么,行号保持不变

    select * from
    (
    select *,rank() over(partition by Grade order by Score desc) as Sequence from Student
    )T where T.Sequence<=2

    执行结果:

  • 相关阅读:
    easy-ui的data-options用法
    my_note
    定时器
    abp安装
    微信小程序
    几个免费的ui 后台
    abp创建实体的方法
    winform 开源项目
    func委托
    for update 锁行和锁表
  • 原文地址:https://www.cnblogs.com/yxlblogs/p/7093191.html
Copyright © 2011-2022 走看看