问题
I have a table like:
colA | colB
" " | 1
"K 111" | 1
"K222" | 2
" " | 3
Some columns have only a space (" "), some have "K {number}", some have "K{number}".
If colA has a space I want that value replaced with the one from colB.
So endresult should be:
colA | colB
1 | 1
"K abc" | 1
"Kdef" | 2
3 | 3
How can I do this?
回答1:
You can use a case
expression:
select (case when colA = ' ' then to_char(col_b)
else colA
end) as new_colA
If you wanted to be more general, you might use like
:
select (case when colA like 'K%' then colA
else
end) as new_colA
In an update
, you would move the when
condition to a filtering condition:
update t
set colA = to_char(colb)
where colA = ' ';
回答2:
You can use a case
expression:
select
case when cola = ' ' then to_char(colb) else cola end as cola,
colb
from mytable
Note that all branches of a case
expression must return values of the same datatype. It seems like colb
is a number, so this converts it to a string.
回答3:
Or, DECODE
function (just an alternative to 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>
回答4:
Yet another option is to update the value using IS NULL
check as follows:
update your_table
set colA = to_char(colB)
where trim(colA) is null;
Empty string in Oracle is considered as null.
来源:https://stackoverflow.com/questions/65114394/fill-rows-in-column-a-with-value-of-column-b-if-condition-in-column-a-is-met