偶然在論壇看到一個網友的帖子,關於他遇到一個面試題的,網站寫了不少,我看了一下,結果應該是沒問題的,可是爲什麼面試官仍是不滿意,我想面試官可能並非想考你真能把這道題作出來,而是看你如何簡潔的經過一個sql語句就完成,重點我想是面試官想看到"row_number" "partition"這樣的關鍵字吧面試
下面說下具體分析作法sql
有個成績表 StuScore(StuId,Subject,Score)分別爲學號,課程名,成績。測試
問題:用語句查詢出每科的前三名學生的學號網站
1.建立測試sql語句spa
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.查詢語句:code
select * from ( select *,ROW_NUMBER() over(partition by Subject order by Score desc) RN from StuScore ) T where RN<4
3.結果以下:blog