我有一个类似的结构:
country: | state: | city: | citizen:
id | id | id | id
name | name | name | age
| country_id | state_id | city_id
| | |
我需要的结果如下:
country_name | state_name | city_name | citizens
----------------------------------------------------
India | MH | Mumbai | 45
USA | California | LA | 234
USA | Washington | Seattle | 324
我尝试的查询是:
SELECT
country.name AS "country_name",
state.name AS "state_name",
city.name AS "city_name",
count(citizen.id) AS "citizens"
FROM citizen
LEFT JOIN city on citizen.city_id = city.id
LEFT JOIN state on city.state_id = state.id
LEFT JOIN country on state.country_id = country.id
WHERE
citizen.age > 50
GROUP BY city_name;
Postgres给我的错误是:
ERROR: column "state.name" must appear in the GROUP BY clause
or be used in an aggregate function
LINE 3: state.name AS "state_name",
我不确定如何实现我所需要的。