如何在以下T-SQL语句中避免重复的子查询:
update r set
column1=(select top 1 max(column1) from region r2 where (overlapping test conditions)),
column2=(select top 1 max(column2) from region r2 where (overlapping test conditions))
from region r
基本上,我有一个包含矩形区域的表格。对于每个重叠区域,我需要将一些列设置为该重叠区域的聚合值。
由于
编辑:我在这里添加了一个过度简化的重叠条件:
(r.left >= r2.left and r.left < r2.right) or (r.right <= r2.right and r.right > r.left)
重点是:r和r2都将在子查询中引用。对于常见的表表达式来说,这似乎是一个完美的情况,但我无法弄清楚如何将它用于每个记录。
答案 0 :(得分:1)
UPDATE Region
SET
Region.Column1 = r.Column1
Region.Column2 = r.Column2
FROM
Region
INNER JOIN
(
SELECT
Column1,
Column2
FROM Region
WHERE (your condition here)
) r ON r.ID = Region.ID
我刚注意到MAX()aggs。对不起第一次看到了。 你可能必须有两个内连接才能使它工作......
所以拿我所拥有的并为column1
做INNER JOIN (SELECT MAX(Column1) FROM ... WHERE ... ) r ON r.ID = Region.ID
然后是第二次INNER JOIN
INNER JOIN (SELECT MAX(Column2) FROM ... WHERE ...)r2 ON r2.ID = Region.ID
您的更新将变为
UPDATE Region
SET Region.Column1 = r1.Column1,
Region.Column2 = r2.Column2
FROM Region
INNER JOIN
(SELECT MAX(Column1) as Column1 FROM ... WHERE ... ) r ON r.ID = Region.ID
INNER JOIN
(SELECT MAX(Column2) As Column2 FROM ... WHERE ... ) r2 ON r2.ID = Region.ID