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.
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.
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 ...
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.
Answer: D.GROUP BY clause must contain all the columns appearing in the SELECT statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With