Oracle SQL将值从另一列提取到新列?

时间:2019-05-06 05:06:32

标签: sql oracle ddl

基本上,我正在尝试创建一个表,该表的列的值是从单独表的地址列的邮政编码部分中提取的。地址列是一个字符串,其中包含街道地址,城市,州和邮政编码,每个地址都用逗号分隔。

仅供参考,整个数据集中的逗号格式都一致。如何设置此格式?以下是我用来尝试创建表的代码。

CREATE TABLE CHILD_TABLE
 (ZipCode NUMBER REFERENCES 
  PARENT_TABLE(substr(address,instr(address,',',-1)+2)));

1 个答案:

答案 0 :(得分:0)

这是一个显示如何从地址字符串中提取邮政编码的选项-使用正则表达式,取最后一个词

SQL> with addr (addr) as
  2    -- this is the "address column"
  3    (select 'Muppet street,London,England,12345' from dual)
  4  select regexp_substr(addr, '\w+$') zipcode
  5  from addr;

ZIPCO
-----
12345

SQL>

[编辑:将邮政编码插入另一个表中]

这是方法。

SQL> -- Table that contains addresses
SQL> create table t1 (addr varchar2(50));

Table created.

SQL> insert into t1
  2    select 'Muppet street,London,England,12345' from dual union all
  3    select 'Batman road,Berlin,Germany,9948'    from dual union all
  4    select 'Ilica,Zagreb,Croatia,10000'         from dual;

3 rows created.

SQL> -- A new table, containing ZIP codes
SQL> create table t2 (zipcode number);

Table created.

SQL> -- Insert zip codes from the address into the new table
SQL> insert into t2 (zipcode)
  2    select regexp_substr(t1.addr, '\w+$')
  3    from t1;

3 rows created.

SQL> select * From t2;

   ZIPCODE
----------
     12345
      9948
     10000

SQL>