代码之家  ›  专栏  ›  技术社区  ›  wingyip

使用表1中另一行的值更新表1中的行,以查找表2中的值

  •  0
  • wingyip  · 技术社区  · 5 年前

    我有一张桌子如下

    表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
    

    我需要使用Type='companyid'中的值为同一个UserId更新TABLE1中的Type='branchid'。一旦我有了正确的'companyid',我想用下面的SELECT从表2中得到最上面的BranchId

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

    如何在一个Update语句中实现这一点?

    1 回复  |  直到 5 年前
        1
  •  3
  •   sellotape    5 年前

    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'
    
        2
  •  0
  •   M. Kanarkowski    5 年前

    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