首页 > 解决方案 > 在SQL中从没有以下字符的字符串中提取数字

问题描述

所以我有如下街道地址:

123 Street Ave
1234 Road St Apt B
12345 Passage Way 

现在,我很难在没有任何街道名称的情况下仅提取街道编号。

我只是想:

123
1234
12345

标签: sqloracle

解决方案


正如您所说,两个简单的选项会返回所需的结果。一个使用正则表达式(选择字符串中的第一个数字),而另一个返回第一个子字符串(由空格分隔)。

SQL> with test (address) as
  2    (select '123 Street Ave' from dual union all
  3     select '1234 Road St Apt B' from dual union all
  4     select '12345 Passage Way' from dual
  5   )
  6  select
  7    address,
  8    regexp_substr(address, '^\d+') result_1,
  9    substr(address, 1, instr(address, ' ') - 1)  result_2
 10  from test;

ADDRESS            RESULT_1           RESULT_2
------------------ ------------------ ------------------
123 Street Ave     123                123
1234 Road St Apt B 1234               1234
12345 Passage Way  12345              12345

SQL>

推荐阅读