Skip to content
Advertisement

Error Referencing Sub Query in Group By on Main Select statement in T-SQL

I am trying to run the following T-SQL code

Example:

Order table

Item table

Result:

I need to be able to count the number of items for that order per month and year however,

I am getting this error

Column ‘Order Reference’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Even though it is not used in the main select?

Any help appreciated

Advertisement

Answer

You are using it in the main SELECT, because it is being fed into the correlated subquery.

Instead, you can do this as a join, then sum that up. I’ve done this as an APPLY but you could also do a JOIN

Note that EOMONTH can be more efficient as a grouping value than YEAR and DATENAME, so try this

Side note: COUNT(NonNullValue) is the same as COUNT(*) or COUNT(1)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement