1

I have 2 tables that will match on a value, let's call it PersonID. Here are the tables:

Table1

ID   |   Field   |   Value
-----|-----------|--------
1    |   Loc1    |   faf  
1    |   Loc1    |   0653
2    |   Loc1    |   5711  
3    |   Loc1    |   9669
4    |   Loc1    |   ado  
4    |   Loc1    |   6843  
5    |   Loc1    |   rfc  
6    |   Loc1    |   cba 


Table2
ID   |   Loc1    |   Loc2
-----|-----------|--------
1    |   faf     |   0653  
2    |           |   5711
3    |           |   9669  
4    |   ado     |   6843  
5    |   rfc     |         
6    |   cba     |         

I accidentally inserted the value Loc1 for the Field in Table1. I need to update it based on the name of the colomn from Table2.

How can I update Table1 by searching for the Table1.Value column in Table2 and then taking the column name. I need it to end up looking like this:

ID   |   Field   |   Value
-----|-----------|--------
1    |   Loc1    |   faf  
1    |   Loc2    |   0653
2    |   Loc2    |   5711  
3    |   Loc2    |   9669
4    |   Loc1    |   ado  
4    |   Loc2    |   6843  
5    |   Loc1    |   rfc  
6    |   Loc1    |   cba 

NOTE: All Loc2 values are not numbers and All Loc1 values are not letters. I just used those values for simplicity sake.

4

1 回答 1

0

这可以使用基本CASE来完成,以确定其中的哪一列包含列中Table2引用的值:valueTable1

UPDATE t1
SET Field = 
CASE 
    WHEN t1.Value = t2.Loc1 THEN 'Loc1' 
    WHEN t1.Value = t2.Loc2 THEN 'Loc2' 
END
FROM Table1 t1
JOIN Table2 t2
    ON t1.ID = t2.ID

我假设这只是您的实际数据/表结构的简化版本,但您可能会考虑的是,如果这两个表应该包含相同的信息,那么您实际上并不需要这两个表。

相反,可以从任一表中透视或取消透视数据,以便根据需要在另一个表的结构中获取结果。

于 2013-10-16T16:02:34.327 回答