首页 > 解决方案 > 如何有条件地更改列值

问题描述

我想根据以下条件更改列值。感谢您对此的专家建议。如果在 col_lst 中找到该列,我需要为相应的列值“F~”添加前缀。我可以通过sql查询来实现吗?

Current Output:
row_id|col_lst|col1|col2|col3|col4
1|col1,col2|1|2|3|4
2|col3,col4|A|B|C|D
3|col2|X|Y|Z|P

Expected Output:
row_id|col_lst|col1|col2|col3|col4
1|col1,col2|F~1|F~2|3|4
2|col3,col4|A|B|F~C|F~D
3|col2|X|F~Y|Z|P

问候

米希尔

标签: sqlplsql

解决方案


您可以对每个列名使用 INSTR 函数来确定它是否在 col_lst 列中。

with test_data(row_id,col_lst,col1,col2,col3,col4) as 
   ( select  1, 'col1,col2', '1', '2', '3', '4' from dual union all  
     select  2, 'col3,col4', 'A', 'B', 'C', 'D' from dual union all  
     select  3, 'col2',      'X', 'Y', 'Z', 'P' from dual 
   )
select row_id
     , col_lst
     , case when instr(col_lst,'col1')>0 then 'F~' || nvl(col1,' ') else col1 end col1 
     , case when instr(col_lst,'col2')>0 then 'F~' || nvl(col2,' ') else col2 end col2 
     , case when instr(col_lst,'col3')>0 then 'F~' || nvl(col3,' ') else col3 end col3 
     , case when instr(col_lst,'col4')>0 then 'F~' || nvl(col4,' ') else col4 end col4
from test_data;

但是,在这种情况下,您应该只告诉其他团队不。没有任何东西是他们无法从 col_lst 自己确定的,除了输出格式之外,它没有任何用途 - 表示层应该这样做。


推荐阅读