如何使用连接自身检索的数据更新表?

Bra*_*ann 8 sql sql-server sql-server-2008

我有以下数据:

SectorKey Sector foo  
1         A      null 
2         B      null
...       ...    ...
1         null   a  
2         null   b 
2         null   c 
1         null   d 
2         null   e 
...       ...    ...
Run Code Online (Sandbox Code Playgroud)

我希望根据sectorKey的值更新列为Sector时的扇区,即当SectorKey为1时我希望Sector为'A',而当SectorKey为2时我想要'B'

我试过这个查询:

update tbFoo
set Sector=A.sector 
from tbFoo A INNER JOIN tbFoo B
ON A.SectorKey=B.SectorKey 
and A.Sector is not null 
and B.Sector is null
Run Code Online (Sandbox Code Playgroud)

并收到此错误消息:

表'tbFoo'含糊不清.

我试过别名第一个tbFoo,但它似乎不是一个有效的语法.我不明白为什么SQLServer抱怨模糊的命名,因为我的所有表都有别名.

我找到了这个帖子,我觉得我在做的事情与在upvoted答案中完全一样.我也尝试了在接受的答案中建议的查询:

    update tbFoo A
    set Sector = 
       (select Sector from tbFoo 
        where A.SectorKey=SectorKey and Sector is not null)
Run Code Online (Sandbox Code Playgroud)

然后SQLServer抱怨"A"附近的语法不正确

关于可能发生的事情的任何想法,并解决这个问题?我正在使用SQLServer 2008.

编辑我没有显示我的表的总数据.我不只有两个案例(A和B),而是几千个案例.所以一个明确的案例不是一个选择

Joe*_*orn 22

使用更新查询第一部分中的别名:

update B
set Sector=A.sector 
from tbFoo A INNER JOIN tbFoo B
ON A.SectorKey=B.SectorKey 
and A.Sector is not null 
and B.Sector is null
Run Code Online (Sandbox Code Playgroud)

否则,它不知道要更新的表的哪个实例.