首页 > 解决方案 > 根据Redshift sql中另一列的条件从列中删除字符

问题描述

我有一个表,我想在其中执行以下操作:如果 col_1 具有值“sakc”或“cosc”,则从 col_2 的这些行中删除出现的字符“_”。

例子:

给定 table_1

col_1            col_2

sakc             abc_aw
sakc             asw_12
cosc             absd12
dasd             qwe_32
cosc             dasd_1

所需的表_1

col_1            col_2

sakc             abcaw
sakc             asw12
cosc             absd12
dasd             qwe_32
cosc             dasd1   

我尝试使用以下内容:

select case when col_1 in ('sakc', 'cosc') then trim("_" from col_2) end col_2 from table_1;

但我确信这不是正确的方法并且给了我错误。

标签: sqlamazon-redshift

解决方案


您可以使用replace()

SELECT  
  col_1
 ,CASE 
    WHEN col_1 in ('sakc', 'cosc') THEN REPLACE(col_2, '_', '')
    ELSE col_2 
  END col2 
FROM table_1;

推荐阅读