【问题标题】:mysql use group by column in where conditionmysql在where条件下按列使用
【发布时间】:2011-03-09 15:07:18
【问题描述】:

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

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.....

它没有帮助。

谢谢

【问题讨论】:

    标签: mysql group-by aggregate-functions mysql-error-1111


    【解决方案1】:
    SELECT column1.....,SUM(Hits) AS HitsSum 
    FROM table 
    GROUP BY column1.....
    HAVING HitsSum > 100
    

    【讨论】:

      【解决方案2】:
      SELECT column1.....,SUM(Hits) AS Sum_Hits   
      FROM table 
      GROUP BY column1.....
      HAVING Sum_Hits > 100
      

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 2011-09-02
          • 1970-01-01
          • 2021-10-26
          • 2012-04-14
          • 2011-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多