2

我正在尝试编写一个查询来计算和列出学生的 GPA,然后只显示低于所有学生平均 GPA 的那些。我已成功获得查询以输出每个学生的 GPA 表,但我无法让它仅显示低于平均水平的表。

以下是我当前的查询:

    SELECT SC.StudentID, S.StdLastName, GPA
    FROM (SELECT SC.StudentID, S.StdLastName, ROUND(SUM(C.Credits * GV.GradeValue)/SUM(C.Credits), 2) AS GPA
         FROM ((Student_Classes AS SC INNER JOIN GradeValues AS GV ON SC.Grade = GV.Grade) 
         INNER JOIN Students AS S ON SC.StudentID = S.StudentID)
         INNER JOIN Classes as C ON SC.ClassID = C.ClassID
         GROUP BY SC.StudentID, S.StdLastName)
    GROUP BY SC.StudentID, S.StdLastName, GPA
    HAVING GPA < AVG(GPA)
    ORDER BY GPA;

当我这样做时,出现的错误是,

您尝试执行的查询不包含指定表达式 GPA < AVG(GPA) 作为聚合函数的一部分。

我在这个网站上发现了多个类似错误的页面,但仍然无法正常工作。任何帮助将非常感激。

4

2 回答 2

3

当您说 时GROUP BY SC.StudentID, S.StdLastName, GPA,您是在告诉数据库使用这三列来创建数据组,然后AVG在每个组中应用聚合函数(在本例中)。这意味着,正如所写,您正在尝试根据该学生的平均水平过滤每个学生的 GPA。希望每个学生的平均 GPA 等于他们的实际 GPA...

为了完成这项工作,您需要第二个子查询,您可以使用它来获取总体平均 GPA:

SELECT sc.studentid, s.stdlastname, gpa
FROM   (SELECT sc.studentid, 
               s.stdlastname, 
               ROUND(SUM(c.credits * gv.gradevalue) / SUM(c.credits), 2) AS gpa
        FROM      ((student_classes sc
              INNER JOIN gradevalues gv
                 ON sc.grade = gv.grade)
              INNER JOIN students s
                 ON sc.studentid = s.studentid)
        GROUP BY sc.studentid, s.stdlastname)
GROUP BY sc.studentid, s.stdlastname, gpa
WHERE gpa < (SELECT AVG(GPA) as avg_gpa 
               FROM (SELECT ROUND(SUM(c.credits * gv.gradevalue) / SUM(c.credits), 2) AS gpa
                     FROM  student_classes sc
                           INNER JOIN gradevalues gv
                                   ON sc.grade = gv.grade
                     GROUP BY sc.studentid))
ORDER BY gpa;

我不确定这是否会解决您的语法问题,但它应该可以解决您的逻辑问题。

于 2013-03-04T21:15:33.273 回答
0

这是否摆脱了错误?如果是这样,您可以从中选择 sid、lname 和 GPA

  SELECT SC.StudentID, S.StdLastName, GPA, avg(GPA) as avgGPA
FROM (SELECT SC.StudentID, S.StdLastName, ROUND(SUM(C.Credits * GV.GradeValue)/SUM(C.Credits), 2) AS GPA
     FROM ((Student_Classes AS SC INNER JOIN GradeValues AS GV ON SC.Grade = GV.Grade) 
     INNER JOIN Students AS S ON SC.StudentID = S.StudentID)
     INNER JOIN Classes as C ON SC.ClassID = C.ClassID
     GROUP BY SC.StudentID, S.StdLastName)
WHERE GPA < avg(GPA)
GROUP BY SC.StudentID, S.StdLastName, GPA
    ORDER BY GPA;
于 2013-03-04T19:56:22.280 回答