Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column invalid in select list even though it's in aggregate

Here is my query:

SELECT ScriptName
      ,BranchName
      ,AVG(Passes) OVER (PARTITION BY ScriptName, BranchName) AS AvgPasses
FROM temp3
GROUP BY ScriptName, BranchName

Here is my error:

Column 'temp3.Passes' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I understand GROUP BY. Does the OVER PARTITION BY mean it won't work with GROUP BY? I haven't been able to find anything on MSDN. If it does mean it won't work, can someone explain why? I cannot think of a circumstance in which a problem would arise from this.

like image 737
sirdank Avatar asked Feb 28 '14 22:02

sirdank


People also ask

How do you fix the error column is invalid in the SELECT list because it is not contained in either an aggregate function or the GROUP BY clause?

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.

What is invalid in the SELECT list because it is not contained in either an aggregate function or GROUP BY Claus?

Basically, what this error is saying is that if you are going to use the GROUP BY clause, then your result is going to be a relation/table with a row for each group, so in your SELECT statement you can only "select" the column that you are grouping by and use aggregate functions on that column because the other columns ...

Can SELECT be used with aggregate functions?

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.

Do all columns in a SELECT list have to appear in a GROUP BY clause?

Answer: D.GROUP BY clause must contain all the columns appearing in the SELECT statement.


1 Answers

Yes, the over partition by means that it will not work with group by. So remove it:

SELECT ScriptName, BranchName,
       AVG(Passes) AS AvgPasses
FROM temp3
GROUP BY ScriptName, BranchName;

Technically, the reason is because Passes is not in the group by and not in an aggregation function.

First, if Passes is an integer, the average will also be an integer. If you want a floating point average, then convert the value to the appropriate type.

Second, analytic functions do work with group by. For instance, if you wanted the sum of all the averages, you could do:

SELECT ScriptName, BranchName,
       AVG(Passes) AS AvgPasses,
       SUM(AVG(Passes)) over (ScriptName, BranchName) as SumAvg
FROM temp3
GROUP BY ScriptName, BranchName;

Ok, that seems weird. But the min() and max() might be useful.

like image 141
Gordon Linoff Avatar answered Oct 06 '22 21:10

Gordon Linoff