web-dev-qa-db-ja.com

エラーコード1111。グループ関数の無効な使用

だからこれは動作します:

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
16
user3374108

したがって、この条件を[〜#〜] 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
29
Surabhil Sergy

Where句で集計関数を使用していますが、これはSQLではできません。

代わりに [〜#〜] having [〜#〜] 句を使用します。

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