簡體   English   中英

SQL UPDATE語句,用於根據另一個現有行更新列

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

基本上我有一個表格,其格式與下表相似。

我想要做的是根據這個邏輯更新Col4

  • 如果Col2為null,則使用Col3更新Col4
  • 如果Col2不為null,則在Col1中找到與Col2中的值匹配的值。 使用col3中的相應值更新col4

例如,給定此表:

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

將其更新為此表

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

任何方向將不勝感激!

這樣的東西應該工作(未經測試):

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

這應該讓你測試它:

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

希望這可以幫助,

皮特

這樣的事情可能會在Oracle中發揮作用。

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

當然,如果select col3 from myTable where col1 = col2返回多行,則此查詢將不起作用。 但我想你已經知道你的數據是否足夠干凈以便它可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM