SQL Server AVG函数错误

时间:2015-03-19 14:42:14

标签: sql sql-server group-by average

我有两个SQL Server表...

MODULES        ENROLMENTS
GroupNo        StudentNo
Title          GroupNo
Tutor          CourseworkMark
DayNo          ExamMark
Time
Room
Semester

在Access中,我创建了一个基于另一个表的表单,该表保存了课程编号和名称的记录。对于每门课程,我希望创建一个关于该特定课程中模块的子表格。

在子窗体视图中,我希望拥有GroupNo,Title,Tutor,DayNo,Time,Room,Semester,CourseworkMark的平均值和ExamMark的平均值。

我构建了这个查询

SELECT tblEnrolments.GroupNo, Tutor, DayNo, Time, Room, Semester, 
       AVG(CourseworkMark) AS AvgCourseworkMark, AVG(ExamMark) AS AvgExamMark
FROM tblEnrolments INNER JOIN tblModules ON tblEnrolments.GroupNo = tblModules.GroupNo
GROUP BY tblEnrolments.GroupNo;

然而,我收到了错误

  

Msg 8120,Level 16,State 1,Line 1   专栏' tblModules.Tutor'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我跑的时候。如何获取查询中的Tutor,DayNo,Time,Room和Semester字段,因为它们不属于GROUP BY或AVG。谢谢

2 个答案:

答案 0 :(得分:0)

您必须按选择列表中的所有值进行分组,因此查询将如下所示:

SELECT tblEnrolments.GroupNo, Tutor, DayNo, Time, Room, Semester, 
       AVG(CourseworkMark) AS AvgCourseworkMark, AVG(ExamMark) AS AvgExamMark
FROM tblEnrolments INNER JOIN tblModules ON tblEnrolments.GroupNo = tblModules.GroupNo
GROUP BY tblEnrolments.GroupNo, Tutor, DayNo, Time, Room, Semester;

答案 1 :(得分:0)

正如此错误所说

  

Msg 8120,Level 16,State 1,Line 1 Column' tblModules.Tutor'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

并在评论中提及 @Gordon Linoff:

您需要在

中包含组中的所有非聚合列
SELECT tblEnrolments.GroupNo, 
                     Tutor, 
                     DayNo, 
                     Time, 
                     Room, 
                     Semester, 
                     AVG(CourseworkMark) AS AvgCourseworkMark, 
                     AVG(ExamMark) AS AvgExamMark
FROM tblEnrolments 
INNER JOIN tblModules ON tblEnrolments.GroupNo = tblModules.GroupNo
GROUP BY tblEnrolments.GroupNo ,Tutor, DayNo, Time, Room, Semester ;