偶然在论坛看到一个网友的帖子,关于他遇到一个面试题的,网站写了很多,我看了一下,结果应该是没问题的,但是为何面试官还是不满意,我想面试官可能并不是想考你真能把这道题做出来,而是看你如何简洁的通过一个sql语句就完成,重点我想是面试官想看到"row_number" "partition"这样的关键字吧
下面说下具体分析做法
有个成绩表 StuScore(StuId,Subject,Score)分别为学号,课程名,成绩。
问题:用语句查询出每科的前三名学生的学号
1.创建测试sql语句
create table StuScore(StuId int,Subject nvarchar(10),Score float); insert into StuScore values(1,'语文',70);
insert into StuScore values(1,'数学',60);
insert into StuScore values(1,'英语',90); insert into StuScore values(2,'语文',78);
insert into StuScore values(2,'数学',67);
insert into StuScore values(2,'英语',80); insert into StuScore values(3,'语文',89);
insert into StuScore values(3,'数学',60);
insert into StuScore values(3,'英语',97); insert into StuScore values(4,'语文',50);
insert into StuScore values(4,'数学',67);
insert into StuScore values(4,'英语',70); insert into StuScore values(5,'语文',79);
insert into StuScore values(5,'数学',65);
insert into StuScore values(5,'英语',79); insert into StuScore values(6,'语文',74);
insert into StuScore values(6,'数学',56);
insert into StuScore values(6,'英语',87);
2.查询语句:
select * from (
select *,ROW_NUMBER() over(partition by Subject order by Score desc) RN from StuScore
) T where RN<4
3.结果如下: