2014-03-12 54 views
5

我正在創建一個查詢,並且在某種程度上我的查詢中似乎存在問題。在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中

這裏是我的查詢:

Select 
E.last_name as [Last Name], 
E.first_name as [First Name], 
SUM(CASE WHEN empAttendance.status = 'Absent' THEN 1 ELSE 0 END) as [Absences], 
SUM(CASE WHEN empAttendance.status = 'Late' THEN 1 ELSE 0 END) as [Number of Lates] 
from 
empAttendance 
INNER JOIN employee E ON empAttendance.emp_id = E.emp_id 
WHERE E.company_id = (Select company_id from company Where company_name = @company) 

其中僱員表具有emp_id列這是它的PK,也是empAttendance有EMP_ID爲FK。

員工表有last_namefirst_name列。

錯誤說:提前Column 'employee.last_name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

感謝。

+0

不管你信不信,返回的錯誤信息都是準確的,並且是一個處理錯誤的方法。當您逐列向GROUP BY添加列時,它可能會逐級迭代,但那是經驗的代價。 –

回答

4

當使用聚合函數SUM需要group by

Select 
E.last_name as [Last Name], 
E.first_name as [First Name], 
SUM(CASE WHEN empAttendance.status = 'Absent' THEN 1 ELSE 0 END) as [Absences], 
SUM(CASE WHEN empAttendance.status = 'Late' THEN 1 ELSE 0 END) as [Number of Lates] 
from 
empAttendance 
INNER JOIN employee E ON empAttendance.emp_id = E.emp_id 
WHERE E.company_id = (Select company_id from company Where company_name = @company) 
GROUP BY E.last_name, E.first_name 
0

問題從你的錯誤信息是顯而易見的。在集合函數的情況下使用GROUP BY

Select 
E.last_name as [Last Name], 
E.first_name as [First Name], 
SUM(CASE WHEN empAttendance.status = 'Absent' THEN 1 ELSE 0 END) as [Absences], 
SUM(CASE WHEN empAttendance.status = 'Late' THEN 1 ELSE 0 END) as [Number of Lates] 
from 
empAttendance 
INNER JOIN employee E ON empAttendance.emp_id = E.emp_id 
WHERE E.company_id = (Select company_id from company Where company_name = @company) 
GROUP BY E.last_name, E.first_name 
+0

在我的情況下,當我使用分組時,我現在有「缺席」字段= 0和10在另一行重複值..同樣晚了 –

相關問題