Here are my two tables:
Table1 +-----------+-----------+-------+-------+----------+ | Address1 | Address2 | Unit1 | Unit2 | Precinct | +-----------+-----------+-------+-------+----------+ | 150 | Oak St | 0 | 10 | 1111 | +-----------+-----------+-------+-------+----------+ Table2 +-----------+-----------+-------+-------+----------+ | Address1 | Address2 | Unit1 | Unit2 | Precinct | +-----------+-----------+-------+-------+----------+ | 150 | Oak St | 0 | 10 | 1111 | | 150 | Oak St | 0 | 10 | 2222 | +-----------+-----------+-------+-------+----------+ What I'm trying to do is copy date from Table2 (source) over to Table1 (target) like this:
- Match on Address1, Address2, Unit1, Unit2
- if precinct is the same, don't do anything
- if precinct is different, append with a comma ("1111" to "1111, 2222")
This is what I tried:
UPDATE t1 SET t1.Precinct = CASE WHEN t1.Precinct LIKE '%' + t2.Precinct + '%' THEN t1.Precinct ELSE t1.Precinct + ',' + t2.Precinct END FROM Table1 t1 join Table2 t2 on t1.Address1 = t2.Address1 and t1.Address2 = t2.Address2 and t1.Unit1 = t2.Unit1 and t1.Unit2 = t2.Unit2 My expected result is this:
Expected Result (Table1) +-----------+-----------+-------+-------+-----------+ | Address1 | Address2 | Unit1 | Unit2 | Precinct | +-----------+-----------+-------+-------+-----------+ | 150 | Oak St | 0 | 10 | 1111,2222 | +-----------+-----------+-------+-------+-----------+ but what I get is this:
Actual Result (Table1) (Nothing changes) +-----------+-----------+-------+-------+-----------+ | Address1 | Address2 | Unit1 | Unit2 | Precinct | +-----------+-----------+-------+-------+-----------+ | 150 | Oak St | 0 | 10 | 1111 | +-----------+-----------+-------+-------+-----------+ I played around with it a little bit and found out that since the match on (address1, address2, unit1, unit2) has 2 results in the Source table, the query only ends up looking at the first row (precinct=1111) and never looking at the second row.
How can I work around this? Is my current approach the complete wrong approach?
Precinct. You could usestring_aggto get thePrecinctvalue.