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

通过从另一个表获取数据来更新列

  •  0
  • SP1  · 技术社区  · 6 年前

    我有一张下面的桌子

    Code APAC APACRatio EMEA EMEARatio
    SL   2               4
    PQ   5               5
    

    我还有一张桌子

    Code Count
    SL    3
    PQ    4
    

    我必须根据代码更新第一个表,以便得到下面的结果

    Code APAC APACRatio EMEA EMEARatio
     SL   2     2/3       4   4/3
     PQ   5     5/4       10  10/4
    

    所以我想通过加入代码然后更新来计算比率。我可以手动一列一列地做,但不确定是否有动态的方法。

    1 回复  |  直到 6 年前
        1
  •  2
  •   S3S    6 年前

    直进与除法连接

    select 
    t1.Code
    ,t1.[APAC APACRatio] / t2.[Count]
    ,t1.[EMA EMEARatio] / t2.[Count]
    from table 1 t1
    inner join table2 t2 on t1.Code = t2.Code
    

    或者,可能是串联?

    select 
    t1.Code
    ,concat(t1.[APAC APACRatio],'/',t2.[Count])
    ,concat(t1.[EMA EMEARatio],'/',t2.[Count])
    from table 1 t1
    inner join table2 t2 on t1.Code = t2.Code
    

    因此,

    update t1
        set 
         t1.[APAC APACRatio] =  concat(t1.[APAC APACRatio],'/',t2.[Count])
        ,t1.[EMA EMEARatio] = concat(t1.[EMA EMEARatio],'/',t2.[Count])
        from table1 t1
        inner join table2 t2 on t1.Code = t2.Code