column不包含在aggregate function或group by子句中

时间:2016-03-04 06:45:55

标签: sql-server

我正在尝试选择使用sum的查询行。我不断收到错误column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.我将指定的列添加到group by子句中,它只是转到查询中的下一列。我是否真的必须将select子句中的每一列添加到group by子句中?

这是我的疑问:

SELECT 
   s.studentId, s.firstName, s.lastName, 
   c.courseId, c.courseName, c.semesterId AS courseSemesterId, 
   se.semesterId, se.season, se.year, 
   e.enrollmentId, e.studentId AS enrolledStudentId, e.courseId AS enrolledCourseId, e.semesterId AS enrolledSemesterId,
   a.assignmentId, (sum(a.pointsEarned) / sum(a.pointsPossible)) AS percentage
FROM Students AS s
INNER JOIN Enrollment AS e ON s.studentId = e.studentId
LEFT JOIN Courses AS c ON e.courseId = c.courseId
LEFT JOIN Semesters AS se ON c.semesterId = se.semesterId
LEFT JOIN Assignments AS a ON e.enrollmentId = a.enrollmentId
GROUP BY s.studentId, s.firstName, s.lastName
ORDER BY e.courseId

2 个答案:

答案 0 :(得分:1)

不一定,如果您使用SQL Server 2012或更高版本(我相信),您可以使用OVER子句,如下所示:

(sum(a.pointsEarned) OVER (PARTITION BY s.studentId) / 
 sum(a.pointsPossible) OVER (PARTITION BY s.studentId))

链接到msdn文章:OVER Clause

答案 1 :(得分:0)

试试这样。

方法-1

SELECT s.studentId
    ,s.firstName
    ,s.lastName
    ,(sum(a.pointsEarned) / sum(a.pointsPossible)) AS percentage
FROM Students AS s
INNER JOIN Enrollment AS e ON s.studentId = e.studentId
LEFT JOIN Courses AS c ON e.courseId = c.courseId
LEFT JOIN Semesters AS se ON c.semesterId = se.semesterId
LEFT JOIN Assignments AS a ON e.enrollmentId = a.enrollmentId
GROUP BY s.studentId
    ,s.firstName
    ,s.lastName
ORDER BY e.courseId

方法-2(如果您需要选择中的所有列。您应该将其包含在分组中)

SELECT s.studentId
    ,s.firstName
    ,s.lastName
    ,c.courseId
    ,c.courseName
    ,c.semesterId AS courseSemesterId
    ,se.semesterId
    ,se.season
    ,se.year
    ,e.enrollmentId
    ,e.studentId AS enrolledStudentId
    ,e.courseId AS enrolledCourseId
    ,e.semesterId AS enrolledSemesterId
    ,a.assignmentId
    ,(sum(a.pointsEarned) / sum(a.pointsPossible)) AS percentage
FROM Students AS s
INNER JOIN Enrollment AS e ON s.studentId = e.studentId
LEFT JOIN Courses AS c ON e.courseId = c.courseId
LEFT JOIN Semesters AS se ON c.semesterId = se.semesterId
LEFT JOIN Assignments AS a ON e.enrollmentId = a.enrollmentId
GROUP BY s.studentId
    ,s.firstName
    ,s.lastName
    ,c.courseId
    ,c.courseName
    ,c.semesterId
    ,se.semesterId
    ,se.season
    ,se.year
    ,e.enrollmentId
    ,e.studentId
    ,e.courseId
    ,e.semesterId
    ,a.assignmentId
ORDER BY e.courseId