简体   繁体   中英

Update table multiple column values from another table multiple rows by matching IDs

I'm Trying to update Table-A (Col1, Col2, Col3) values from Table B (Row1, Row2, Row3) by matching ColID & mapping_id in Row.

Table - A

ColID Col1 Col2 Col3
A null null null
B null null null
C null null null

Table - B

RowID Value mapping_id Col
1 1a (this value goes to A-Col1) A Col1
2 2a (this value goes to A-Col2) A Col2
3 3a (this value goes to A-Col3) A Col3
4 1b (this value goes to B-Col1) B Col1
5 2b (this value goes to B-Col2) B Col2
6 3b (this value goes to B-Col3) B Col3

Expected Output

ColID Col1 Col2 Col3
A 1a 2a 3a
B 1b 2b 3b
C null null null

My query:

update Table-A
SET Col1 = (select value
            from Table-B
            where Table-A.ColID = Table-B.mapping.id
            and TableB.Col = 'Col1');

When I run this code it's updating Table-A Col1

Like this

ColID Col1 Col2 Col3
A 1a null null
B 1b null null
C null null null

I'm having more than 30 columns in table, I can't update one by one.

You can first apply a pivoting operation using:

  • CASE operations to extract the corresponding " Value_ " values for each of the columns
  • MAX operations to aggregate rows and select only non-null " Col1 ", " Col2 ", " Col3 " values

Once you have your " Table B " so wrangled (which we're calling " cte " ), you can carry out the UPDATE statement and set " TableA.Col " to the corresponding " cte.Col " values. You can match values between two tables inside an UPDATE statement with a JOIN operation.

WITH cte AS (
    SELECT mapping_id, 
           MAX(CASE WHEN Col = 'Col1' THEN Value_ END) AS Col1,
           MAX(CASE WHEN Col = 'Col2' THEN Value_ END) AS Col2,
           MAX(CASE WHEN Col = 'Col3' THEN Value_ END) AS Col3
    FROM tabB
    GROUP BY mapping_id
)
UPDATE     tabA
INNER JOIN cte
        ON tabA.ColID = cte.mapping_id
SET tabA.Col1 = cte.Col1,
    tabA.Col2 = cte.Col2,
    tabA.Col3 = cte.Col3;

Check the demo here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM