19

所以这有效:

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

但我只需要获取大于 30 的 city_population_percent 值,所以我试试这个:

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

那是我得到的时候:

错误代码1111。无效使用组功能

也就是说,当我在以下条件中添加此条件时它会失败WHERE

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

2 回答 2

39

所以你必须把这个条件移到HAVING子句

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
于 2014-03-03T08:37:33.353 回答
6

您在 where 子句中使用聚合函数,这是在 SQL 中无法做到的。

改用HAVING子句:

WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30
于 2014-03-03T08:37:17.160 回答