简体   繁体   中英

SQL UPDATE statement to update a column based on another existing row

Basically I have a table that has similar format to the below table.

What I want to do is update Col4 based on this logic

  • if Col2 is null then update Col4 with Col3
  • if Col2 is not null then find the the value in Col1 which matches the value in Col2. update col4 with with the corresponding value in col3

For example given this table:

| Col1 | Col2 | Col3 | Col4 |
-----------------------------
|  1   |   2  |  A1  |  2   |
-----------------------------
|  2   |   3  |  A2  |  3   |
-----------------------------
|  3   |{null}|  A3  |{null}|

Update it to be this table

| Col1 | Col2 | Col3 | Col4 |
-----------------------------
|  1   |   2  |  A1  |  A2  |
-----------------------------
|  2   |   3  |  A2  |  A3  |
-----------------------------
|  3   |{null}|  A3  |  A3  |

Any direction would be greatly appreciated!

Something like this should work (untested):

UPDATE  table
SET     col4 = CASE WHEN table.col2 IS NULL THEN table.col3 ELSE col2Matches.col3 END
FROM    table
        INNER JOIN table AS col2Matches
            ON  table.col2 = col2Matches.col1

this should let you test it:

SELECT  CASE WHEN table.col2 IS NULL THEN table.col3 ELSE col2Matches.col3 END
FROM    table
        INNER JOIN table AS col2Matches
            ON  table.col2 = col2Matches.col1

Hope this helps,

Pete

Something like this would probably work in Oracle.

update myTable
set col4 = case when col2 is null then col3
                else (select col3 from myTable where col1 = col2)
           end;

Of course, if select col3 from myTable where col1 = col2 returns multiple rows then this query will not work. But I imagine you know already know if your data is clean enough for this to work.

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