1

我有三张桌子。

表格1:

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

StudentName

表 2:

Studentmarks

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

subjectId

marks

表3:

Subject
---------
subjectID

subjectName

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

我想要像这样的输出:

----------------------------------------------------------------
    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
4

1 回答 1

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;
于 2013-07-11T12:25:58.843 回答