Ani*_*ita 3 sql amazon-redshift
我正在 AWS Redshift 上进行 URL 提取。URL 列如下所示:
url item origin
http://B123//ajdsb apple US
http://BYHG//B123 banana UK
http://B325//BF89//BY85 candy CA
Run Code Online (Sandbox Code Playgroud)
我想要得到的结果是获取以 B 开头的系列,并且如果 URL 中有多个系列,还可以扩展行。
extracted item origin
B123 apple US
BYHG banana UK
B123 banana UK
B325 candy CA
BF89 candy CA
BY85 candy CA
Run Code Online (Sandbox Code Playgroud)
我当前的代码是:
select REGEXP_SUBSTR(url, '(B[0-9A-Z]{3})') as extracted, item, origin
from data
Run Code Online (Sandbox Code Playgroud)
正则表达式部分运行良好,但我在提取多个值并将它们扩展到新行时遇到问题。我尝试使用REGEXP_MATCHES(url, '(B[0-9A-Z]{3})', 'g'),但 Redshift 上不存在函数 regexp_matches...
小智 5
我使用的解决方案相当丑陋,但达到了预期的结果。它涉及使用REGEXP_COUNT来确定一行中的最大匹配数,然后使用 将结果数字表连接到查询REGEXP_SUBSTR。
-- Get a table with the count of matches
-- e.g. if one row has 5 matches this query will return 0, 1, 2, 3, 4, 5
WITH n_table AS (
SELECT
DISTINCT REGEXP_COUNT(url, '(B[0-9A-Z]{3})') AS n
FROM data
)
-- Join the previous table to the data table and use n in the REGEXP_SUBSTR call to get the nth match
SELECT
REGEXP_SUBSTR(url, '(B[0-9A-Z]{3})', 1, n) AS extracted,
item,
origin
FROM data,
n_table
-- Only keep non-null matches
WHERE n > 0
AND REGEXP_COUNT(url, '(B[0-9A-Z]{3})') >= N
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4131 次 |
| 最近记录: |