在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中

时间:2014-03-12 08:49:42

标签: sql-server sql-server-2008 select

我正在创建一个查询,不知怎的,我的查询中似乎出现了问题。

这是我的问题:

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)

其中employee表的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.

提前致谢。

1 个答案:

答案 0 :(得分: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