sql语句查询成绩表各科前三名
--语法形式: ROW_NUMBER() OVER(PARTITION BY COL1 ORDER BY COL2)
--解释: 根据COL1分组,在分组内部根据 COL2排序,⽽此函数计算的值就表⽰每组内部排序后的顺序编号(组内连续的唯⼀的) --常⽤的使⽤场景:取每个学科的前3名
--1.创建测试表
create table #score
(
name varchar(20),
sql语句查询结果取反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名数据
select * from
(
select subject,name,score,ROW_NUMBER() over(PARTITION by subject order by score desc) as num from#score
) T where T.num <= 3 order by subject
--4.删除临时表 drop table #score
结果:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论