views:

221

answers:

1

How can I avoid the duplicated subquery in the following T-SQL statement:

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

Basically, I have a table containing rectangle regions. For each overlapped region, I need to set some columns to the aggregation values of that overlapped region.

Thanks

EDIT: I am adding a over-simplified overlap condition here:

(r.left >= r2.left and r.left < r2.right) or (r.right <= r2.right and r.right > r.left)

The point is: both r and r2 will be referenced in the subquery. It seems like this is a perfect situation for common table expression but I cannot figure out how to use it for each record.

A: 
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

I just noticed the MAX() aggs. Sorry didnt see that the first time. You will have to probably have two inner joins to make that work...

so take what I have and do it for column1

INNER JOIN (SELECT MAX(Column1) FROM ... WHERE ... ) r ON r.ID = Region.ID 

Then a second INNER JOIN

INNER JOIN (SELECT MAX(Column2) FROM ... WHERE ...)r2 ON r2.ID = Region.ID   

And your update becomes

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
JonH
@JonH: the dup subquery was what I was trying to avoid. Besides, I updated my original question to show what the where clause may look like. It seems like the condition cannot be accepted in such a subquery (The multi-part identifier "r.left" could not be bound).
Codism
Ok you hadnt mentioned that in the beginning sorry.Let me take another look, so you want to avoid having two SELECT's to update two different fields correct?
JonH
Yeah, any idea?
Codism
I dont think you can due to the use of MAX on 2 different fields. The aggregates complicates it, otherwise I would have an answer sorry.
JonH