The reason a column is not valid in the select list is that it is not included in an aggregate function or GROUP BY clause
P粉517090748
2023-08-23 14:36:31
<p>I received an error - </p>
<blockquote>
<p>Column 'Employee.EmpID' is not valid in the select list because it is
Not included in aggregate functions or GROUP BY clauses. </p>
</blockquote>
<hr />
<pre class="brush:php;toolbar:false;">select loc.LocationID, emp.EmpID
from Employee as emp full join Location as loc
on emp.LocationID = loc.LocationID
group by loc.LocationID</pre>
<p>This situation matches the answer given by Bill Karwin. </p>
<p>Correction to above, answer suitable for ExactaBox - </p>
<pre class="brush:php;toolbar:false;">select loc.LocationID, count(emp.EmpID) -- not count(*), don't want to count nulls
from Employee as emp full join Location as loc
on emp.LocationID = loc.LocationID
group by loc.LocationID</pre>
<hr />
<p><strong>Original question -</strong></p>
<p>For SQL queries -</p>
<pre class="brush:php;toolbar:false;">select *
from Employee as emp full join Location as loc
on emp.LocationID = loc.LocationID
group by (loc.LocationID)</pre>
<p>I don't understand why this error occurs. All I want to do is join the tables and then group all employees at a specific location together. </p>
<p><strong>I think I partially explained my problem. Tell me if you can -</strong> </p>
<p>To group all employees working at the same location, we must first mention the LocationID. </p>
<p>Then we can't/don't mention each employee ID next to it. Instead we mention the total number of employees at the location i.e. we should SUM() the employees working at that location. I'm not sure why we go the latter way.
So this explains the "it is not contained in either aggregate function" part of the error. </p>
<p>What is the explanation for the incorrect <strong><code>GROUP BY</code></strong> clause part? </p>
If you set disable
ONLY_FULL_GROUP_BY
server mode (by default), your queries will run inMYSQL
. But in this case, you are using a different RDBMS. So to make your query work, add all non-aggregated columns to yourGROUP BY
clause, likeNon-aggregated column means that the column will not be passed to aggregate functions, such as
SUM
,MAX
,COUNT
, etc.Suppose I have the following table
T
:I execute the following query:
The output should have two lines, one for
a=1
and the second fora=2
.But what should the value of b be displayed in these two lines? There are three possibilities for each case, and nothing in the query makes it clear which value to choose for b in each group. The meaning is very vague.
This demonstrates the single value rule which prohibits getting undefined results when running a GROUP BY query and including any column criteria in the select list that is not part of the grouping and will not appear in in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
Now it's obvious that you want the following result: