我有一个表格如下
表1
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
和表2
BranchId CompanyId Name
1 123 RedBranch
2 123 YellowBranch
3 123 GreenBranch
4 124 SouthBranch
5 125 NorthBranch
我需要更新 TABLE1 中的类型,其中类型 = '分支 id' 使用同一用户 ID 的类型 = '公司 id' 中的值。 一旦我有了正确的"公司ID",我想使用以下选择从表2中获取TOP BranchId
SELECT TOP 1 Id
FROM TABLE2
WHERE CompanyId = (correct companyid from TABLE1)
ORDER BY Id DESC
如何在一个更新语句中实现此目的?
这里有一个刺
: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'
我不确定我是否完全理解这个问题,但也许......
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