You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PostgreSQL中用ST_Area()按地域类型-类别组合统计总面积?

解决方案

直接用聚合函数SUM()对每个分组的面积求和,同时不要将geom加入GROUP BY——你需要的是按iso_country_code、country_code、territory_type、territory_category组合汇总的总面积,而非单个要素的面积。

正确的SQL查询如下:

SELECT 
    iso_country_code, 
    country_code, 
    territory_type, 
    territory_category,
    COUNT(*) AS feature_count,
    SUM(ST_Area(geom::geography)/1000000) AS total_area_km2
FROM "table"
GROUP BY iso_country_code, country_code, territory_type, territory_category;

关键说明:

  • COUNT(*)可替代你之前的count(territory_type||territory_category),效果一致且更简洁。
  • SUM(ST_Area(...))会将同一分组下所有要素的面积相加,得到该组合的总面积。
  • 移除GROUP BY中的geom,确保分组仅基于你需要的四个字段,这样就能得到预期的13条结果。

内容的提问来源于stack exchange,提问作者danaburtono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 11:22:32