从现有列中SQL新列

  • 本文关键字:SQL 新列 sql oracle
  • 更新时间 :
  • 英文 :


我有一个包含两列的表:

column1        column2
1              ID1_1
2              ID2_2
3              ID3

我想在第二列的值的基础上添加第三列。如果该值包含下划线,我希望按下划线拆分该值并使用第一部分。如果该值不包含下划线,我只想插入相同的值:

column1        column2      column3
1              ID1_1        ID1
2              ID2_2        ID2
3              ID3          ID3

如何在SQL中执行此操作?

有各种选项;以下是其中的几个:

  • one(col3_a(使用正则表达式并获取第一个单词(这就是_!取代的原因(
  • 另一个(col3_b(使用搜索_的事例表达式;如果存在,则取其前面的子字符串。否则,取字符串本身
  • 或者,再次使用正则表达式-在字符串的开头使用字母数字(col3_c(

SQL> with test (col1, col2) as
2    (select 1, 'ID1_1' from dual union all
3     select 2, 'ID2_2' from dual union all
4     select 3, 'ID3'   from dual
5    )
6  select col1, col2,
7    regexp_substr(replace(col2, '_', '!'), 'w+') col3_a,
8    --
9    case when instr(col2, '_') > 0 then substr(col2, 1, instr(col2, '_') - 1)
10         else col2
11    end col3_b,
12    --
13    regexp_substr(col2, '^[[:alnum:]]+') col3_c
14  from test;
COL1 COL2  COL3_A COL3_B COL3_C
---------- ----- ------ ------ ------
1 ID1_1 ID1    ID1    ID1
2 ID2_2 ID2    ID2    ID2
3 ID3   ID3    ID3    ID3
SQL>

如果要向表中添加新列,则alter它并更新新添加列的值。

SQL> select * from test;
COL1 COL2
---------- -----
1 ID1_1
2 ID2_2
3 ID3
SQL> alter table test add col3 varchar2(10);
Table altered.
SQL> update test set
2    col3 = case when instr(col2, '_') > 0 then substr(col2, 1, instr(col2, '_') - 1)
3                else col2
4           end;
3 rows updated.
SQL> select * from test;
COL1 COL2  COL3
---------- ----- ----------
1 ID1_1 ID1
2 ID2_2 ID2
3 ID3   ID3
SQL>

如果您可以使用,生成的列功能将派上用场:

alter table mytable 
add column3 as (regexp_substr(column2, '^[^_]+', 1));

sqlfiddle

最新更新