我有一个多边形的Zones层和一个Address Points层。
以下查询完成:
SELECT zones.OBJECTID, Avg(address.WalkTime)
FROM address
JOIN zones
ON zones.Shape.STContains(address.Shape) = 1
GROUP BY mb.OBJECTID
╔══════════╦════════════════╗
║ OBJECTID ║ No column Name ║
╠══════════╬════════════════╣
║ 31 ║ 8.1 ║
║ 41 ║ 5.3 ║
║ 55 ║ 12.5 ║
║ 78 ║ 10.4 ║
║ 94 ║ 9.7 ║
╚══════════╩════════════════╝
我在区域中有一个新的空数字列,称为 Avg_WalkTime
如何调整查询以将平均值插入此列?
尝试:
UPDATE
zones
SET
zones.Avg_WalkTime = (
SELECT Avg(address.WalkTime)
FROM address
WHERE zones.Shape.STContains(address.Shape) = 1
但是,由于语法错误,此操作会失败吗?
答案 0 :(得分:1)
您不能OBJECTID
同时更新,因为行已分组并且指向基础原始行的链接“丢失”。
您可以使用CTE或子查询来计算平均值,然后通过一组可以正确标识行的列连接回原始表。我假设这是这种情况下的;WITH Averages AS
(
SELECT
zones.OBJECTID,
Average = Avg(address.WalkTime)
FROM
address
JOIN zones ON zones.Shape.STContains(address.Shape) = 1
GROUP BY
zones.OBJECTID
)
UPDATE Z set
Avg_WalkTime = A.Average
FROM
zones AS Z
INNER JOIN Averages AS A ON Z.OBJECTID = A.OBJECTID
。
zones
另一个使用相关子查询的解决方案。即使address
上没有匹配的行,此行也会更新所有NULL
(将平均值设置为INNER JOIN
)。前一个只会更新地址至少为1(UPDATE Z SET
Avg_WalkTime = (SELECT Avg(A.WalkTime) FROM address AS A WHERE Z.Shape.STContains(A.Shape) = 1)
FROM
zones AS Z
)的区域。
{{1}}