从表中选择前3名

时间:2013-07-11 12:23:19

标签: sql sql-server-2008 tsql

我有三张桌子。

表1:

Student
----------
studentID

StudentName

表2:

Studentmarks

----------------
studentID

subjectId

marks

表3:

Subject
---------
subjectID

subjectName

我需要一个查询来获得每个科目的前三名学生。

我希望输出如下:

----------------------------------------------------------------
    StudentID         Name    subjectId    subjectName    marks
-----------------------------------------------------------------
       1               AAA        1           phy        85
       2               BBB        1           phy        75
       3               CCC        1           phy        65
       3               CCC        2           bio        85
       4               DDD        2           bio        75
       1               AAA        2           bio        65
       6               FFF        3           che        85
       1               AAA        3           che        75
       5               EEE        3           che        65
       3               CCC        4           mat        85
       2               BBB        4           mat        75
       4               DDD        4           mat        65

1 个答案:

答案 0 :(得分:4)

WITH CTE
AS
(
   SELECT
     s.StudentID,
     s.StudentName,
     sm.subjectId,
     j.SubjectName,
     sm.marks,
     ROW_NUMBER() OVER(PARTITION BY sm.subjectId 
                       ORDER BY sm.marks DESC) AS RN
   FROM student AS s
   INNER JOIN Studentmarks AS sm ON s.studentID  = sm.studentID
   INNER JOIN Subject      AS j  ON sm.subjectId = j.SubjectId
)
SELECT
  StudentID,
  StudentName,
  subjectId,
  SubjecTName,
  marks
FROM CTE
WHERE RN <= 1;