[英]SQL UPDATE statement to update a column based on another existing row
基本上我有一個表格,其格式與下表相似。
我想要做的是根據這個邏輯更新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.