>  기사  >  데이터 베이스  >  mssql row_number和partition by分组取排名前3数据

mssql row_number和partition by分组取排名前3数据

WBOY
WBOY원래의
2016-06-07 17:48:331934검색

我们经常会要统计一个表中前几名学习成绩好的记录,下面我们利用了sql的row_number()函数,row_number()函数的分组排序功能使这种操作变得非常简单的,有需要的朋友参考一下。

 代码如下 复制代码

--1.创建测试表
create table #score
(
    name varchar(20),
    subject varchar(20),
    score int
)
--2.插入测试数据
insert into #score(name,subject,score) values('张三','语文',98)
insert into #score(name,subject,score) values('张三','数学',80)
insert into #score(name,subject,score) values('张三','英语',90)
insert into #score(name,subject,score) values('李四','语文',88)
insert into #score(name,subject,score) values('李四','数学',86)
insert into #score(name,subject,score) values('李四','英语',88)
insert into #score(name,subject,score) values('李明','语文',60)
insert into #score(name,subject,score) values('李明','数学',86)
insert into #score(name,subject,score) values('李明','英语',88)
insert into #score(name,subject,score) values('林风','语文',74)
insert into #score(name,subject,score) values('林风','数学',99)
insert into #score(name,subject,score) values('林风','英语',59)
insert into #score(name,subject,score) values('严明','英语',96)
--3.取每个学科的前3名数据
* from
(
    select subject,name,score,ROW_NUMBER() over(PARTITION by subject order by score desc) as num from #score
) T where T.num --4.删除临时表
truncate table #score
drop table #score

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.