我正在尝试编写一个计算并列出学生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&lt; AVG(GPA)作为聚合函数的一部分。
我在此网站上发现了类似错误的多个网页,但仍无法使其正常运行。任何帮助将不胜感激。
答案 0 :(得分: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;
我不确定这是否会解决你的语法问题,但它应该解决你的逻辑问题。
答案 1 :(得分: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;