[英]Create a column and fill it with a certain value if another condition in a different table is met?
[英]Fill rows in column A with value of column B if condition in column A is met
我有一張像這樣的桌子:
colA | colB
" " | 1
"K 111" | 1
"K222" | 2
" " | 3
有些列只有一個空格(“”),有些列有“K {number}”,有些有“K {number}”。
如果 colA 有空格,我希望將該值替換為 colB 中的值。
所以最終結果應該是:
colA | colB
1 | 1
"K abc" | 1
"Kdef" | 2
3 | 3
我怎樣才能做到這一點?
您可以使用case
表達式:
select (case when colA = ' ' then to_char(col_b)
else colA
end) as new_colA
如果你想更通用,你可以使用like
:
select (case when colA like 'K%' then colA
else
end) as new_colA
在update
中,您可以將when
條件移動到過濾條件:
update t
set colA = to_char(colb)
where colA = ' ';
您可以使用case
表達式:
select
case when cola = ' ' then to_char(colb) else cola end as cola,
colb
from mytable
請注意, case
表達式的所有分支都必須返回相同數據類型的值。 看起來colb
是一個數字,所以這會將它轉換為一個字符串。
或者, DECODE
function(只是CASE
的替代):
SQL> with test (cola, colb) as
2 (select 'K 111', 1 from dual union all
3 select ' ' , 1 from dual union all
4 select 'K222' , 2 from dual union all
5 select ' ' , 3 from dual
6 )
7 select decode(cola, ' ', to_char(colb), cola) cola,
8 colb
9 from test;
COLA COLB
---------- ----------
K 111 1
1 1
K222 2
3 3
SQL>
另一種選擇是使用IS NULL
檢查更新值,如下所示:
update your_table
set colA = to_char(colB)
where trim(colA) is null;
Oracle 中的空字符串被認為是 null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.