下面的代码运行良好,除了我确定 threshold AS
的步骤。它不是计算在 polygon_dump AS
步骤中创建的每个栅格的计数,而是将所有栅格一起计算。我一直在尝试使用 GROUP BY,但收效甚微。
WITH
-- Select Features
feat AS
(SELECT toid AS building_id,
wkb_geometry AS geom
FROM buildings
),
polygon_dump AS
(SELECT (ST_DumpAsPolygons(ST_Clip(a.st_roughness,1,b.geom,-9999,true))).val AS polygon_vals,building_id AS building_id2
FROM grosvenor_raster_roughness a, feat b
),
threshold AS
(SELECT Count(*) AS thres_val
FROM polygon_dump
WHERE polygon_vals >= 0 AND polygon_vals < 0.5
GROUP BY building_id2
),
b_stats AS
(SELECT building_id, (stats).*
FROM (SELECT building_id, ST_SummaryStats(ST_Clip(a.st_roughness,1,b.geom,-9999,true)) AS stats
FROM grosvenor_raster_roughness a
INNER JOIN feat b
ON ST_Intersects(b.geom,a.st_roughness)
) AS foo
)
-- Summarise statistics
SELECT count As pixel_count,
thres_val AS threshold_val,
cast(thres_val as real)/cast(count as real)*100 AS percent_value,
min AS min_pixel_val,
max AS max_pixel_val,
mean AS avg_pixel_val,
stddev AS pixel_stddev
FROM b_stats, threshold
WHERE count > 0;
我得到以下结果:
红色的两列是正确的结果,我需要做什么才能只得到这些结果?
最佳答案
您正在进行交叉连接。您需要将带有 building_id
的列添加到您的 threshold
CTE 中,以便您可以使用 b_stats
加入它。我不确定它应该是 LEFT 还是 INNER JOIN,所以我要使用 INNER。
WITH
-- Select Features
feat AS
(SELECT toid AS building_id,
wkb_geometry AS geom
FROM buildings
),
polygon_dump AS
(SELECT (ST_DumpAsPolygons(ST_Clip(a.st_roughness,1,b.geom,-9999,true))).val AS polygon_vals,building_id AS building_id2
FROM grosvenor_raster_roughness a, feat b
),
threshold AS
(SELECT building_id2 AS building_id, Count(*) AS thres_val
FROM polygon_dump
WHERE polygon_vals >= 0 AND polygon_vals < 0.5
GROUP BY building_id2
),
b_stats AS
(SELECT building_id, (stats).*
FROM (SELECT building_id, ST_SummaryStats(ST_Clip(a.st_roughness,1,b.geom,-9999,true)) AS stats
FROM grosvenor_raster_roughness a
INNER JOIN feat b
ON ST_Intersects(b.geom,a.st_roughness)
) AS foo
)
-- Summarise statistics
SELECT count As pixel_count,
thres_val AS threshold_val,
cast(thres_val as real)/cast(count as real)*100 AS percent_value,
min AS min_pixel_val,
max AS max_pixel_val,
mean AS avg_pixel_val,
stddev AS pixel_stddev
FROM b_stats
JOIN threshold USING(building_id)
WHERE count > 0;
关于postgresql - Postgresql中如何正确使用GROUP BY函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51476865/