2

I am trying to use some basic SQL functions. I need to get an average of some data and order it in descending order. The error I get is "group function is not allowed"

Table:

STUDENTS
-----------
ID
CLASS
GRADE
ROOM

SQL:

    SELECT ID, class, AVG(Grade) AS AvgGrade
      FROM Students
     GROUP BY AVG(Grade)
    HAVING AVG(Grade) >= 3.0
     ORDER BY AVG(Grade) DESC

I was told that ORDER BY cannot be used with the HAVING clause and I would need to repeat the function. Any help?

0

3 Answers 3

5

GROUP BY avg(Grade) doesn't make any sense.

The GROUP BY expression defines the groups that you want the aggregate applied to.

Presumably you need GROUP BY ID, class

4

You cannot have avg(Grade) under GROUP BY.

In your example, you'd have to have: GROUP BY ID, class.

0

In Standard SQL, only AS clauses ("column aliases") from the SELECT clause are allowed in the ORDER BY clause i.e.

SELECT ID, class, AVG(Grade) AS AvgGrade
  FROM Students
 GROUP BY ID, class
HAVING AVG(Grade) >= 3.0
 ORDER BY AvgGrade DESC;

Not all SQL products faithfully implement Standards, of course, but the above should work in SQL Server, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.