So, you’ve constructed a SQL statement with a GROUP BY clause, and you’re getting this message:
Column col is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Bear in mind that the result of a GROUP BY statement, or of a statement where one or columns uses an aggregate function, has each row containing a summary of other rows.
This means that if you try to include a column in your select clause that isn’t a summary (this includes values by which you’re grouping), then the server is going to have difficulties returning it; remember, it’s going to return one row per group, and any value that can’t be reduced to a single row per group will fail.
This gets interesting even when you’re hoping to return a single value per group, for example with CASE.
If the CASE expression you’re using is dependent on values of individual rows rather than summaries, you’ll also get the above message; you may only reference non-aggregate values (i.e. single-row values) in an aggregate function, or in the WHERE clause, so the solution would involve placing your CASE inside an aggregate function, in this case your SUM.
The same applies for the HAVING clause, as it is effectively selecting rows in the grouped resultset based on values in each group.