zoukankan      html  css  js  c++  java
  • 分析函数partition by

    partition by

    分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是:分析函数对于每个组返回多行,而聚合函数对于每个组只返回一行

    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)
    

    img

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

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

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

    执行结果:

    img

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

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

    执行结果:

    img

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

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

    执行结果:

    img

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

    rank()和dense_rank()区别:

    • rank()是跳跃排序,有两个第二名时接下来就是第四名;
    • dense_rank()l是连续排序,有两个第二名时仍然跟着第三名

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

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

    执行结果:

    img

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

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

    执行结果:

    img

  • 相关阅读:
    翻译《Writing Idiomatic Python》(三):变量、字符串、列表
    Jetson TK1刷机+配置Mini PCI-e无线网卡
    翻译《Writing Idiomatic Python》(二):函数、异常
    翻译《Writing Idiomatic Python》(一):if语句、for循环
    用Python和摄像头制作简单的延时摄影
    安卓加固之so文件加固
    Windbg+VirtualBox双机调试环境配置(XP/Win7/Win10)
    Sizeof Class
    32位和64位系统内核函数调用从ZwProtectVirtualMemory到NtProtectVirtualMemory
    JNI注册调用完整过程-安卓4.4
  • 原文地址:https://www.cnblogs.com/qzkuan/p/15464470.html
Copyright © 2011-2022 走看看