使用TABLE1中另一行中的值将TABLE1中的行更新为TABLE2中的查找值

时间:2019-05-26 18:22:22

标签: sql sql-server sql-update

我有一张桌子,如下表

TABLE1

Id   UserId  Type       Value
1    AAA     companyid  123
2    AAA     branchid   
3    BBB     companyid  124
4    BBB     branchid   
5    CCC     companyid  125
6    CCC     branchid   

和TABLE2

BranchId   CompanyId   Name
1          123         RedBranch
2          123         YellowBranch
3          123         GreenBranch
4          124         SouthBranch
5          125         NorthBranch

我需要使用相同的UserId的Type ='companyid'中的值来更新TABLE1 WHERE Type ='branchid'中的Type。一旦有了正确的“ companyid”,我想使用以下SELECT从TABLE2获取TOP BranchId

SELECT TOP 1 Id 
FROM TABLE2
WHERE CompanyId = (correct companyid from TABLE1)
ORDER BY Id DESC

如何在一条Update语句中实现这一目标?

2 个答案:

答案 0 :(得分:3)

在这里刺伤

update T1
set Value = (select max(BranchId) from Table2 where CompanyId = T1a.value)
from Table1 T1
inner join Table1 T1a on T1a.UserId = T1.UserId and T1a.Type = 'companyid'
where T1.Type = 'branchid'

答案 1 :(得分:0)

我不确定我是否完全理解问题,但也许...

with maxBranch as
(
select
     max(BranchId) as BranchId
    ,CompanyId
from TABLE2
group by CompanyId
)
update t1
set t1.Value = m.BranchID
from TABLE1 as t1
join TABLE1 as t11
    on t1.UserId = t11.UserId
    and t1.Type = 'branchid'
    and t11.Type = 'companyid' 
join maxBranch as m
    on m.CompanyId = t11.Value