WITH buildings AS
(
SELECT
t_id,
geometrie AS geometrie
FROM
agi_dm01avsoch24.bodenbedeckung_boflaeche
WHERE
art = 'Gebaeude'
AND
ST_Intersects(ST_SetSRID(ST_MakePoint(2611306, 1228084), 2056), geometrie)
)
,
clipped_tiles AS
(
SELECT
ST_Clip(elev.rast, buildings.geometrie) AS rast,
elev.rid,
buildings.t_id
FROM
agi_lidar_2019_ndsm.buildings AS elev
JOIN
buildings
ON ST_Intersects(buildings.geometrie, ST_ConvexHull(elev.rast))
)
,
stats AS
(
SELECT
t_id,
(ST_SummaryStatsAgg(rast, 1, true)).*
FROM
clipped_tiles
GROUP BY
t_id
)
SELECT
buildings.t_id,
buildings.geometrie,
stats.mean AS hoehe
FROM
buildings
LEFT JOIN stats
ON buildings.t_id = stats.t_id
;