我正在尝试识别列中字符串中包含的引用号。该表看起来像这样:
col1 col2
1 fgREF1234fhjdREF1235hgkjREF1236
2 hREF1237hjdfREF1238djhfhs
需要编写一个SQL查询,用于标识“REF”后跟4位数字,并在其自己的行中返回每个数字。
输出应如下所示:
col1 ref
1 REF1234
1 REF1235
1 REF1236
2 REF1237
2 REF1238
我试过了:
select
case when substr(substr(col2, instr(col2, 'REF'), 7), 1, 1) like 'R'
then substr(col2, instr(col2, 'R'), 7) else null end ref
from table
...但这只会识别字符串中的第一个匹配项。
我正在使用Oracle SQL,但理想情况下,该解决方案可以转换为其他SQL变体。
任何帮助将非常感激!
您可以使用由regexp_substr
分隔的connect by level <= regexp_count(col2,'REF')
(字符串REF
中的模式字符串col2
的出现时间)
with t(col1,col2) as
(
select 1,'fgREF1234fhjdREF1235hgkjREF1236' from dual union all
select 2,'hREF1237hjdfREF1238djhfhs' from dual
)
select col1,
regexp_substr(col2,'REF[0-9]+',1,level) as ref
from t
connect by level <= regexp_count(col2,'REF')
and prior col1 = col1
and prior sys_guid() is not null;
您可以使用以下代码获得所需的结果: -
select x.col1, explode(x.ref) as ref from (
select col1,split(trim(regexp_replace(col2,'[^REF0-9]',' ')),' ') as ref
from inp