zoukankan      html  css  js  c++  java
  • sql server 2005中的分区函数用法(partition by 字段)

    分组取TOP数据是T-SQL中的常用查询, 如学生信息管理系统中取出每个学科前3名的学生。这种查询在SQL Server 2005之前,写起来很繁琐,需要用到临时表关联查询才能取到。SQL Server 2005后之后,引入了row_number()函数,row_number()函数的分组排序功能使这种操作变得非常简单。

    create database StudentDB
    go

    use StudentDB
    go

    create table Student  --学生成绩表
    (
     id int,  --主键
     Grade int, --班级
     Score int --分数
    )
    go

    insert Student 
        select 1,1,88
    union all select 2,1,66
    union all select 3,1,75
    union all select 4,2,30
    union all select 5,2,70
    union all select 6,2,80
    union all select 7,2,60
    union all select 8,3,90
    union all select 9,3,70
    union all select 10,3,80

    go

    --所有学生信息
    select * from Student

    id          Grade       Score
    ----------- ----------- -----------
    1           1           88
    2           1           66
    3           1           75
    4           2           30
    5           2           70
    6           2           80
    7           2           60
    8           3           90
    9           3           70
    10          3           80

    (10 行受影响)

    --不分班按学生成绩排名
    select *,ROW_NUMBER() over(order by Score desc) as Sequence from Student

    id          Grade       Score       Sequence
    ----------- ----------- ----------- --------------------
    8           3           90          1
    1           1           88          2
    6           2           80          3
    10          3           80          4
    3           1           75          5
    9           3           70          6
    5           2           70          7
    2           1           66          8
    7           2           60          9
    4           2           30          10

    (10 行受影响)

    --分班后按学生成绩排名
    select *,row_number() over(partition by Grade order by Score desc) as Sequence from Student

    id          Grade       Score       Sequence
    ----------- ----------- ----------- --------------------
    1           1           88          1
    3           1           75          2
    2           1           66          3
    6           2           80          1
    5           2           70          2
    7           2           60          3
    4           2           30          4
    8           3           90          1
    10          3           80          2
    9           3           70          3

    (10 行受影响)

  • 相关阅读:
    使用def文件简化dll导出
    ASP.NET Core MVC 之过滤器(Filter)
    ASP.NET Core 中间件 中间件(Middleware)和过滤器(Filter)的区别
    drf-apiview解读系列二
    干货分享,40个photoshop技能送给你!
    冒泡排序 深度优化
    数据结构与算法_14 _ 排序优化:如何实现一个通用的、高性能的排序函数
    数据结构与算法_12 _ 排序(下):如何用快排思想在O(n)内查找第K大元素
    数据结构与算法_13 _ 线性排序:如何根据年龄给100万用户数据排序
    数据结构与算法_11 _ 排序(上):为什么插入排序比冒泡排序更受欢迎
  • 原文地址:https://www.cnblogs.com/jasonlny/p/4268349.html
Copyright © 2011-2022 走看看