开发者

Error with ORDER BY used with HAVING Clause

开发者 https://www.devze.com 2023-04-06 13:14 出处:网络
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\"

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 开发者_JAVA技巧cannot be used with the HAVING clause and I would need to repeat the function. Any help?


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


You cannot have avg(Grade) under GROUP BY.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消