2016-03-04 87 views
0

我試圖選擇具有使用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 
+1

是的,GROUP BY子句中的所有列必須位於SELECT中,但聚合函數中使用的列除外。 –

+0

那麼你是否希望從'assignments'或者它的每一行獲得聚合值呢?因爲你實際上在你的選擇列表中有'a.assignmentID',這意味着你需要單獨的每一行。 –

回答

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 
1

不一定,如果你使用SQL服務器2012或以上版本(我相信),你可以使用OVER條款,比如:

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

李nk to msdn文章:OVER Clause

相關問題