Domanda

I'm stuck to this error:

Msg 8120, Level 16, State 1, Line 2 Column 'Subjects.off_CODE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I don't know what is wrong with this query.

use Enlistment
go

SELECT Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit, COUNT(Enlistment.off_CODE) FROM Enlistment, Subjects
WHERE Subjects.off_CODE = 11315
GROUP BY Enlistment.off_CODE 
È stato utile?

Soluzione

If the column is selected, it must appear in the GROUP BY clause, unless it is contained in an aggregate function (just like the error message says).

use Enlistment
go

SELECT Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit, COUNT(Enlistment.off_CODE) FROM Enlistment, Subjects
WHERE Subjects.off_CODE = 11315
GROUP BY Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit

So, in your example, the only field that is selected that does not have to be included in the GROUP BY clause is Enlistment.off_CODE because it is used in the aggregate function COUNT (COUNT(Enlistment.off_CODE)). All of the other fields must be included in the GROUP BY clause.

Altri suggerimenti

Did you try this:

GROUP BY Enlistment.off_CODE, Subjects.off_CODE

or

SELECT DISTINCT Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit, COUNT(Enlistment.off_CODE) FROM Enlistment, Subjects
WHERE Subjects.off_CODE = 11315
GROUP BY Enlistment.off_CODE, Subjects.off_CODE

?

You are telling the query to GROUP BY a column that you are not selecting. You will need to make sure that you SELECT the columns that are contained within the GROUP BY field.

@Question3CPO's would work except that it includes Subjects.subj_CODE in the SELECT statement and that is probably not contained within the function.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top