下面的查询获取一个城市和所有相邻城市的 shapefile 中的商店数量(表 SHOPS)会抛出此错误; shapefile 在表 GEO 中:
GroupingError: column "GEO.city_name" must appear in the GROUP BY clause or be used in an aggregate function
我的代码包括
CityAndAdjacent.city_name
,我用GEO.city_name
尝试过。两者都有同样的错误。我还尝试在 CTE 之后的 MAX(CityAndAdjacent.city_name) AS city_name
语句中 SELECT
。这些调整都不起作用。我很感激任何指点。
WITH CityAndAdjacent AS (
SELECT
city_name,
ST_Union(geom) AS city_and_adjacent_geom
FROM
GEO
WHERE
city_name = 'City name'
UNION ALL
SELECT
GEO.city_name,
GEO.geom
FROM
GEO
INNER JOIN
CityAndAdjacent
ON
ST_Intersects(GEO.geom, CityAndAdjacent.city_and_adjacent_geom)
)
SELECT
CityAndAdjacent.city_name,
COUNT(SHOPS.*) AS shop_count
FROM
CityAndAdjacent
LEFT JOIN
SHOPS
ON
ST_Within(SHOPS.geom, CityAndAdjacent.city_and_adjacent_geom)
GROUP BY
CityAndAdjacent.city_name;
在递归查询开始时,您正在
st_union
一个城市的所有多边形,但名称并未聚合。您可以尝试以下可能性:
SELECT
city_name,
ST_Union(geom) AS city_and_adjacent_geom
FROM
GEO
WHERE
city_name = 'City name'
GROUP BY city_name
...
顺便说一句,如果您识别多边形 ID,然后将点连接到各个识别的多边形,您的查询会更加有效。这样做将允许使用空间索引。