mysql 在where条件下使用按列分组

发布于 2024-09-07 10:51:49 字数 431 浏览 6 评论 0原文

我怎样才能使这个查询工作:

SELECT column1.....,SUM(Hits) AS Hits   
FROM table 
WHERE  SUM(Hits) > 100
GROUP BY column1.....

问题是where子句,mysql显示错误:

Error Code : 1111
Invalid use of group function

我尝试将查询更改为:

 SELECT column1.....,SUM(Hits) AS Hits   
    FROM table 
    WHERE  Hits > 100
    GROUP BY column1.....

它没有帮助。

谢谢

How can I make this query work :

SELECT column1.....,SUM(Hits) AS Hits   
FROM table 
WHERE  SUM(Hits) > 100
GROUP BY column1.....

The problem is the where clause, mysql display error :

Error Code : 1111
Invalid use of group function

I try to change the query to :

 SELECT column1.....,SUM(Hits) AS Hits   
    FROM table 
    WHERE  Hits > 100
    GROUP BY column1.....

It did not help.

thanks

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

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

发布评论

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

评论(3

诗酒趁年少 2024-09-14 10:52:31
SELECT column1.....,SUM(Hits) AS Sum_Hits   
FROM table 
GROUP BY column1.....
HAVING Sum_Hits > 100
SELECT column1.....,SUM(Hits) AS Sum_Hits   
FROM table 
GROUP BY column1.....
HAVING Sum_Hits > 100
蓬勃野心 2024-09-14 10:52:14

错误的原因是您不能在 WHERE 子句中使用聚合函数,也不能使用聚合函数对派生列使用列别名。这些只能在 HAVING 子句中使用,该子句需要定义 GROUP BY 子句(如果尚不存在)。

我不建议在 GROUP BY 或 HAVING 子句中使用列别名 - 存在查询无法移植到其他数据库的风险。 SQL Server 是我所知道的唯一支持在 GROUP BY 或 HAVING 子句中使用列别名的数据库。

  SELECT t.column1....., SUM(t.hits) AS HitsSum 
    FROM TABLE t
GROUP BY t.column1.....
  HAVING SUM(t.hits) > 100

The reason for the error is that you can not use aggregate functions, or column aliases to derived columns using aggregate functions, in the WHERE clause. These can only be used in the HAVING clause, which requires defining a GROUP BY clause (if it doesn't already exist).

I don't recommend using the column alias in GROUP BY or HAVING clauses - there's a risk that the query will not be portable to other databases. SQL Server is the only other database that I'm aware of that supports column aliases in the GROUP BY or HAVING clauses.

  SELECT t.column1....., SUM(t.hits) AS HitsSum 
    FROM TABLE t
GROUP BY t.column1.....
  HAVING SUM(t.hits) > 100
扛起拖把扫天下 2024-09-14 10:52:06
SELECT column1.....,SUM(Hits) AS HitsSum 
FROM table 
GROUP BY column1.....
HAVING HitsSum > 100
SELECT column1.....,SUM(Hits) AS HitsSum 
FROM table 
GROUP BY column1.....
HAVING HitsSum > 100
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文