Search code examples
sqlsql-order-byhaving-clause

Error with ORDER BY used with HAVING Clause


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?


Solution

  • 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