简体   繁体   English

MS Access选择按多个字段分组的前n个查询

[英]MS Access Select top n query grouped by multiple fields

This is part 2 of a problem that was already answered by peterm on this board. 这是peterm在这个板上已经回答的问题的第2部分。 Thanks again peterm! 再次感谢peterm!

So I have code that will return the top 3 test scores for a given student. 所以我的代码将返回给定学生的前三个测试分数。 My table looks like the following: 我的表如下所示:

StudentID, Test ID, Score 学生ID,考试ID,分数
1,1, 95 1,1,95
1, 2, 90 1,2,90
1, 3, 90 1,3,90
1, 4, 90 1,4,90
2, 1, 99 2,1,99
2, 2, 95 2,2,95
2, 3, 90 2,3,90
2, 4, 90 2,4,90

Thanks to peterm, I have the following code which will do this for me: 感谢peterm,我有以下代码可以为我这样做:

SELECT StudentID, TestID, TestScore
  FROM MyTable t
 WHERE TestID IN
(
  SELECT TOP 3 TestID 
    FROM MyTable
   WHERE StudentID = t.StudentID 
   ORDER BY TestScore DESC, TestID
)
 ORDER BY StudentID, TestScore DESC, TestID;

My new problem is now I need to add two new fields to the table for Subject and Year, so I need to find the top 3 scores for each Subject-Student-Year combination. 我的新问题现在我需要在主题和年份的表格中添加两个新字段,因此我需要找到每个学科 - 学生 - 年组合的前3个分数。 Once I have the top 3 scores for each combination, I need to average them so that I will have one averaged score of the top 3 scores for each student-subject-year combination. 一旦我得到每个组合的前三个分数,我需要对它们进行平均,这样我将得到每个学生 - 主题 - 年组合的前3个分数的平均分数。 Hopefully, I've explained this clearly enough without having to mock up another table. 希望我能够清楚地解释这一点,而不必嘲笑另一张桌子。

Thanks in advance. 提前致谢。

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. 这是SQLFiddle演示。
Demo as usually is for SQL Server but expected to work in MS Access, maybe with minor syntactic tweaks 演示通常适用于SQL Server,但预计可以在MS Access中运行,可能需要进行少量的语法调整

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM