sql server 2005中的分区函数用法(partition by 字段)

sql server 2005中的分区函数用法(partition by 字段) 

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

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 行受影响)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值