根据另一个 table 中的行值更新 table 中的列

update columns in a table based on row values from another table

我有一个 table TABLE1,其中的数据格式如下:


    id     text       pct
    --     ---      -----
    1        AA        5
    1        BB        3
    1        CC        16
    2        BB        7
    3        CC        13

还有一个 table 表 2:


    id     columnAA      columnBB     columnCC
    --     -------       -------      --------
    1        0             0             0
    2        0             0             0
    3        0             0             0


我想更新 table2 中的列,这样我的结果将如下所示:


    id     columnAA      columnBB     columnCC 
    --     -------       -------      -------- 
    1        5              3             16 
    2        0              7              0 
    3        0              0             13 

我试过这段代码,但它并没有真正起作用。它只更新一列!

    update a
      set columnAA = case when b.text = 'AA' then b.pct else columnAA end
     ,set columnBB = case when b.text = 'BB' then b.pct else columnBB end
     ,set columnCC = case when b.text = 'CC' then b.pct else columnCC end
    from table2 a
    join table1 b
      on a.id = b.id

正如 Tab Allerman 所说,您可以这样做:

UPDATE TABLE2
SET columnAA = (SELECT TABLE1.pct FROM TABLE1 WHERE TABLE1.text = 'AA'AND TABLE2.id = TABLE1.id),
columnBB  = (SELECT TABLE1.pct FROM TABLE1 WHERE TABLE1.text = 'BB'AND TABLE2.id = TABLE1.id),
columnCC  = (SELECT TABLE1.pct FROM TABLE1 WHERE TABLE1.text = 'CC'AND TABLE2.id = TABLE1.id)

编辑:

更仔细地查看您的代码。删除第二个和第三个 'Set',它应该可以工作。您不需要仅在第一个单词 'Set' 之后继续每个单词。