选择TOP谓词

时间:2016-10-04 21:52:59

标签: sql ms-access

我有一个包含StudentID,ClassID,ExamID,SubjectID和Scores字段的表 我试图从每个学生的尝试科目中获得7个最高分的总和。下面的SQL语句给出了前七名学生所有科目的总分:

SELECT TOP 7 Sum(tblScores.Scores) AS Total, tblScores.AdmissionID
FROM tblScores
WHERE (((tblScores.ExamID)=[Forms]![frmReports]![lstC]) AND ((tblScores.ClassID)=[Forms]![frmReports]![lstB]))
GROUP BY tblScores.AdmissionID
ORDER BY Sum(tblScores.Scores) DESC;

从“frmReports”表单

中读取班级和考试标准

任何可以帮助我的人?​​

3 个答案:

答案 0 :(得分:1)

考虑相关子查询来计算得分的运行等级。然后,将此选择查询嵌套在 Score 聚合的派生表中,按每个学生的前7个分数(包括关系)进行筛选:

SELECT main.AdmissionID, Sum(main.Scores) As [Total]
FROM
  (SELECT tblScores.AdmissionID, tblScores.Scores,
         (SELECT Count(*) FROM tblScores sub
          WHERE sub.AdmissionID = tblScores.AdmissionID
          AND sub.Scores >= tblScores.Scores) As ScoreRank
   FROM tblScores
   WHERE (((tblScores.ExamID)=[Forms]![frmReports]![lstC])
     AND  ((tblScores.ClassID)=[Forms]![frmReports]![lstB]))
  ) As main
WHERE main.ScoreRank <= 7   
GROUP BY main.AdmissionID

答案 1 :(得分:0)

试试这个:

SELECT TOP 7 Sum(tblScores.Scores) AS Total, tblScores.AdmissionID
FROM tblScores
HAVING (((tblScores.ExamID)=[Forms]![frmReports]![lstC]) AND ((tblScores.ClassID)=[Forms]![frmReports]![lstB]))
GROUP BY tblScores.AdmissionID
ORDER BY Sum(tblScores.Scores) DESC;

答案 2 :(得分:0)

@ Parfait - 感谢您的指导。我实际上已经调整了你的解决方案以获得一个完美的答案:这是sql:

SELECT Dupe.AdmissionID,Dupe.Scores,Dupe.ScoreRank FROM(SELECT qryFilteredScores.AdmissionID,qryFilteredScores.Scores,(SELECT Count(*)FROM qryFilteredScores AS sub
WHERE sub.AdmissionID = qryFilteredScores.AdmissionID AND sub.Scores&gt; qryFilteredScores.Scores)+ 1 AS ScoreRank FROM qryFilteredScores WHERE(((qryFilteredScores.ExamID)= Forms!frmReports!lstC)And((qryFilteredScores.ClassID)= Forms!frmReports !lstB)))AS Dupe WHERE(((Dupe.Scores)&lt;&gt; 0)AND((Dupe.ScoreRank)&lt; = 7));

或者,您可以使用派生表或存储查询(将派生表保存为此查询中引用的单独对象)并避免内联子查询:

SELECT Dupe.AdmissionID, Total.TotalScore
FROM qryFilteredScores AS Dupe
INNER JOIN
     (SELECT sub.AdmissionID, Sum(sub.Scores) As TotalScore
      FROM qryFilteredScores sub
      WHERE ([AdmissionID]=Dupe.[AdmissionID] 
      AND ((sub.ClassID)=[Forms]![frmReports]![lstB]) 
      AND ((tblScores.ExamID)=[Forms]![frmReports]![lstC]))
      GROUP BY sub.AdmissionID) AS Total
ON Dupe.AdmissionID = Total.AdmissionID 
GROUP BY Dupe.AdmissionID, Total.TotalScore
ORDER BY Dupe.AdmissionID;