1

我有一张像这样的桌子:

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

我怎样才能做到这一点?

4

4 回答 4

1

您可以使用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 = ' ';
于 2020-12-02T18:58:54.020 回答
0

您可以使用case表达式:

select 
    case when cola = ' ' then to_char(colb) else cola end as cola,
    colb
from mytable

请注意,case表达式的所有分支都必须返回相同数据类型的值。看起来像是colb一个数字,所以这会将其转换为字符串。

于 2020-12-02T18:58:54.053 回答
0

或者,DECODE函数(只是 的替代品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>
于 2020-12-02T20:03:42.187 回答
0

另一种选择是使用IS NULLcheck 更新值,如下所示:

update your_table
   set colA = to_char(colB)
 where trim(colA) is null;

Oracle 中的空字符串被视为 null。

于 2020-12-03T02:52:26.643 回答