Sql-Server-2008

科目滿分的學生

  • April 20, 2021

我在獲取每個科目中得分最高的學生姓名時面臨一個問題。

這是我下面的表格

學生姓名 學生成績

第一個是Student桌子,STUD_ID , STUD_NAME第二個是MARKS桌子STUD_ID, SUBJECT, MARKS

你能幫我獲取查詢以檢索STUD_NAME, SUBJECT, MAX(MARKS). 我在下面嘗試過,但在獲取STUD_NAME.

select SUBJECT, MAX(MARKS) as Highest
from MARKS inner join STUDENT
ON STUDENT.STUD_ID = MARKS.STUD_ID
GROUP BY SUBJECT

您可以將 CTE 與RANK()功能一起使用。在這裡閱讀更多:

例子:

WITH ordermarks AS (
   SELECT [STUD_ID],[SUBJECT],[MARKS], RANK() OVER (PARTITION BY [SUBJECT] ORDER BY [MARKS] DESC) AS rn
   FROM marks
)
SELECT [STUD_NAME],[SUBJECT],[MARKS]
FROM ordermarks om
JOIN Students s ON s.[STUD_ID]=om.[STUD_ID] AND rn=1

另一種方法是使用DENSE_RANK()and CROSS APPLY

我在 440K 記錄集*(連結到 pastebin)上測試*了下面的查詢 ,它在 0.01 秒內執行。

select     stud_name as [Student Name]
       , [subject] as [Subject]
       , marks     as [Max Marks]
   from dbo.Marks m
cross apply (select   s.stud_id
                    , s.[subject]
                    , s.marks
                    , dense_rank() OVER (PARTITION BY s.[subject]  ORDER BY s.marks desc) AS drnSub 
             from dbo.student s 
           ) s
                where s.stud_id = m.stud_id 
                    and s.drnSub  = 1

引用自:https://dba.stackexchange.com/questions/116580