Error Code 1111. Invalid use of group function

女生的网名这么多〃 提交于 2019-12-05 11:19:37

问题


So this works:

SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name

But I need to only grab the city_population_percent values greater than 30, so I try this:

SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
**AND ROUND(100*(SUM(ci.population)/c.population)) > 30**
GROUP BY c.name

And that's when I get:

Error Code 1111. Invalid use of group function

That is, it fails when I add this condition in the WHERE:

AND ROUND(100*(SUM(ci.population)/c.population)) > 30

回答1:


So you have to move this condition to the HAVING clause

SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
            FROM country AS c
            JOIN city AS ci
            ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30



回答2:


You're using aggregate functions in a where clause, something you cannot do in SQL.

Use the HAVING clause instead:

WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30


来源:https://stackoverflow.com/questions/22141968/error-code-1111-invalid-use-of-group-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!