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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With