与 HAVING 子句一起使用 ORDER BY 时出错

发布于 2024-12-05 04:50:04 字数 391 浏览 0 评论 0原文

我正在尝试使用一些基本的 SQL 函数。我需要获取一些数据的平均值并按降序排列。我得到的错误是“不允许使用组函数”

表:

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

我被告知 ORDER BY 不能与 HAVING 子句一起使用,我需要重复该函数。有什么帮助吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情仇皆在手 2024-12-12 04:50:04

GROUP BY avg(Grade) 没有任何意义。

GROUP BY 表达式定义您希望应用聚合的组。

大概您需要GROUP BY ID, class

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

梨涡 2024-12-12 04:50:04

GROUP BY 下不能有 avg(Grade)

在您的示例中,您必须具有:GROUP BY ID, class

You cannot have avg(Grade) under GROUP BY.

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

遇见了你 2024-12-12 04:50:04

在标准 SQL 中,ORDER BY 子句中仅允许使用 SELECT 子句中的 AS 子句(“列别名”),即并非

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

所有 SQL 产品当然,忠实地执行标准,但上述内容应该适用于 SQL Server 等。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文