sql - 如何在字符串中查找匹配模式的每种情况并作为行返回
问题描述
我正在尝试识别列中字符串中包含的参考号。该表如下所示:
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;
推荐阅读
- php - 如何在 symfony 中使用自定义 gitlab 存储库
- javascript - 在类“a”中调用的“b”类的模拟方法
- python - 如何自定义单个子图的大小?
- rust - Rust:tokio 可以理解为类似于 Javascripts 的事件循环,或者像它一样使用吗?
- javascript - 如何在不将 java 脚本文件添加到 html 文件脚本的情况下访问 java 脚本中的网页域?
- pandas - 给定列中的特定条件,如何系统地删除 Pandas 行?
- c++ - 如何将函数作为函数参数传递给另一个函数?
- ios - 在 iOS 项目的 xcode 构建期间 Azure 管道失败
- mysql - 使用NodeJS批量插入MySQL后如何立即检索数据?
- amazon-web-services - 无法解析自定义 AWS Ground Truth 标记作业清单 JSONL 文件