如何使用regexp_replace替换两个参数

问题描述 投票:0回答:1

我有下表

id var1
1  M
2  F
3  F
4  F
5  M

我希望此表带有下一个代码

    id var1
    1  0
    2  1
    3  1
    4  1
    5  0

SELECT var1,
       CAST(REGEXP_REPLACE(var1, 'F', '0') as int) as var_new,
       CAST(REGEXP_REPLACE(var1, 'M', '1') as int) as var_new
FROM table;

但是,输出是

    id  var_new var_new
    1   0       null
    2   null    1
    3   null    1
    4   null    1
    5   0       null

我正在Databricks上使用SQL ...

sql databricks
1个回答
0
投票

只需使用case表达式:

select id, (case when var1 = 'M' then 0 else 1 end) as var1
from t;

无需执行任何“替换”。

© www.soinside.com 2019 - 2024. All rights reserved.