mysql - 获取错误 #1111 - 组函数的使用无效

标签 mysql group-by mysql-error-1111

我对这个查询有疑问

SELECT SUM(ROUND( SUM( note=3 ) / count( note=3 ) )) AS AVG, sma_famille.famille
                FROM sma_notes, sma_famille, sma_agents, sma_service_activite
                WHERE sma_famille.id_famille >=14
                AND sma_famille.id_service =9
                AND sma_notes.id_agent >=7
                GROUP BY sma_famille.id_famille

然后我收到错误信息

#1111 - Invalid use of group function

如果有人有这种查询的经验。

这里是查询的一些细节:

我像这样在没有第一个 SUM 的情况下进行查询(这是整个查询代码)

    SELECT ROUND( SUM( note =3 ) / count( note =3 ) ) AS AVG, sma_famille.famille, sma_notes.id_agent
    FROM sma_notes, sma_famille, sma_agents, sma_service_activite
    WHERE sma_famille.id_famille >=14
    AND sma_famille.id_service =9
    AND sma_notes.id_agent >=7
    AND sma_notes.id_agent = sma_agents.id_agent
    AND sma_service_activite.id_activite = sma_notes.id_activite
    AND sma_service_activite.id_famille = sma_famille.id_famille
    GROUP BY sma_famille.id_famille, sma_notes.id_agent

然后我得到如下结果:

    AVG | famille   | id_agent  
    3   |BEL        | 7 
    2   |BEL        | 8 
    1   |BEL        | 9 
    1   |CEL        | 7 
    2   |CEL        | 8 
    1   |CEL        | 9 

但是对于我的查询 who 不起作用:

SELECT SUM(ROUND( SUM( note=3 ) / count( note=3 ) )) AS AVG, sma_famille.famille
    FROM sma_notes, sma_famille, sma_agents, sma_service_activite
        WHERE sma_famille.id_famille >=14
        AND sma_famille.id_service =9
        AND sma_notes.id_agent >=7
        AND sma_notes.id_agent = sma_agents.id_agent
        AND sma_service_activite.id_activite = sma_notes.id_activite
        AND sma_service_activite.id_famille = sma_famille.id_famille
        GROUP BY sma_famille.id_famille

我想得到这个结果:

    AVG | famille
    6   |BEL    
    4   |CEL    

提前致谢

阿基里克斯

干杯

最佳答案

您应该使用 HAVING 子句而不是 WHERE

见下文。

假设我有一个表 Address,列为 CityState

HAVING 用于在聚合发生后检查条件。

WHERE 在聚合发生之前使用。

这段代码:

select City, CNT=Count(1)
From Address
Where State = 'MA'
Group By City

为您提供马萨诸塞州所有城市的数量。

这段代码:

select City, CNT=Count(1)
From Address
Where State = 'MA'
Group By City
Having Count(1)>5

为您提供 MA 中出现 6 次或更多次的所有城市的数量。

另请阅读

Definition, Comparison and Difference between HAVING and WHERE Clause

Where Vs Having .

关于mysql - 获取错误 #1111 - 组函数的使用无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11590100/

相关文章:

sql - Mysql 查询 - 组函数的无效使用

python - Django/Python 不喜欢 FloatField 的 None 值

mysql - 为什么在MYSQL中使用GROUP BY时DISTINCT显示的结果不一样

mysql - 使用 JOOQ 查询 Unix 时间戳

r - 在我的分组计数中使用 R 中的 data.table 重复行

python - Pandas - 每个日期的总和

MySQL错误: #1111 - Invalid use of group function

MySQL select count(*) 语句不包括最小值

mysql - PHP - MySQL INSERT - 发现一个错误后会取消查询的其余部分吗?

mysql - 为什么需要从实体到同一实体的关系表