MS Access Select top n query grouped by multiple fields

后端 未结 1 1631
囚心锁ツ
囚心锁ツ 2020-12-11 23:15

This is part 2 of a problem that was already answered by peterm on this board. Thanks again peterm!

So I have code that will return the top 3 test scores for a give

相关标签:
1条回答
  • 2020-12-11 23:36

    You can do something like this

    SELECT StudentID, Year, Subject,  AVG(TestScore) AS AvgScore
      FROM
    (
      SELECT StudentID, Year, Subject, TestScore
       FROM MyTable t
       WHERE TestID IN
      (
       SELECT TOP 3 TestID 
         FROM MyTable
        WHERE StudentID = t.StudentID
          AND Year = t.Year
          AND Subject = t.Subject
        ORDER BY TestScore DESC, TestID
      )
    ) q
     GROUP BY StudentID, Year, Subject
     ORDER BY StudentID, Year, Subject;
    

    Sample output:

    | STUDENTID | YEAR | SUBJECT | AVGSCORE |
    |-----------|------|---------|----------|
    |         1 | 2012 |       1 |       91 |
    |         1 | 2012 |       2 |       84 |
    |         2 | 2012 |       1 |       94 |
    |         2 | 2012 |       3 |       95 |
    

    Here is SQLFiddle demo.
    Demo as usually is for SQL Server but expected to work in MS Access, maybe with minor syntactic tweaks

    0 讨论(0)
提交回复
热议问题