Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

I was creating a query, and somehow there seems to be a problem in my query.

Here is my query:

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)

Wherein the employee table has the emp_id column which is its PK and also the empAttendance has the emp_id as FK.

employee table has the last_name and the first_name columns.

The error says : 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.

Thanks in advance.

like image 465
Marcus Ang Avatar asked Oct 01 '22 08:10

Marcus Ang


People also ask

How do you solve is invalid in the SELECT list because it is not contained in either an aggregate function or the GROUP BY clause?

Solution: As we know that “group by” return single row, so we need to apply an aggregate function to columns not used in group by clause to avoid this error.

Is with an aggregate function?

An aggregate function is a mathematical computation involving a range of values that results in just a single value expressing the significance of the accumulated data it is derived from.

What is an aggregate function in SQL?

An aggregate function performs a calculation on a set of values, and returns a single value. Except for COUNT(*) , aggregate functions ignore null values. Aggregate functions are often used with the GROUP BY clause of the SELECT statement. All aggregate functions are deterministic.

Is not a valid GROUP BY expression?

This SQL error means that that database is trying to group on something that it can't. Usually, this means that there are aggregates in a dimension definition.


1 Answers

When using aggregate function SUM you need to 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
like image 56
slavoo Avatar answered Oct 18 '22 09:10

slavoo