我想拆分大查询数据表中的字段。
我给你示例案例..
==情况1== 源字段=“idx1-cnt1-name1,idx2-cnt2-name2...相同模式”
Result table
idx | cnt | name |
idx1,cnt1,name1
idx2,cnt2,name2,....
在查询中:
select
regexp_extract(split_col, r'([\d]*)-') as ItemIdx,
regexp_extract(split_col, r'-([\d]*)-') as Cnt,
regexp_extract(split_col, r'-([\d]*)$') as TitleIdx
From (
Select pid,now, split(source field, ',') split_col from (
SELECT * FROM table ))
但是我无法在这种情况下编写代码
此 case 字符串有多个分隔符。
==情况2==
源字符串 =“item1-name1-type1-value1,....相同模式”
Result Table
name | type
name1, type1
name2,type2
字段数不同。
但我只需要第二个、第三个字段值。
如何进行查询..
最佳答案
我看到您正在使用 BigQuery 旧版 sql - 因此下面的示例(注意 - 强烈建议您尽可能使用 BigQuery 标准 SQL - 因此请考虑迁移) - 下面经过简化,以使逻辑更易于您阅读,以便您可以轻松地将其扩展到可能更相似的情况
案例1/示例
#legacySQL
SELECT
REGEXP_EXTRACT(split_col, r'^(.*?)-.*?-.*?$') AS idx,
REGEXP_EXTRACT(split_col, r'^.*?-(.*?)-.*?$') AS cnt,
REGEXP_EXTRACT(split_col, r'^.*?-.*?-(.*?$)') AS name
FROM (
SELECT SPLIT(source_field, ',') split_col
FROM (SELECT "idx1-cnt1-name1,idx2-cnt2-name2" source_field)
)
结果:
Row idx cnt name
1 idx1 cnt1 name1
2 idx2 cnt2 name2
案例 2/示例
#legacySQL
SELECT
REGEXP_EXTRACT(split_col, r'^.*?-(.*?)-.*?') AS name,
REGEXP_EXTRACT(split_col, r'^.*?-.*?-(.*?)-') AS type
FROM (
SELECT SPLIT(source_string, ',') split_col
FROM (SELECT "item1-name1-type1-value1, item2-name2-type2-value2" source_string)
)
结果:
Row name type
1 name1 type1
2 name2 type2
下面是相同的示例,但适用于 BigQuery 标准 SQL(只是情况 2,因为它们非常相似)
#standardSQL
WITH `project.dataset.table` AS (
SELECT "item1-name1-type1-value1, item2-name2-type2-value2" source_string
)
SELECT
REGEXP_EXTRACT(split_col, r'^.*?-(.*?)-.*?') AS name,
REGEXP_EXTRACT(split_col, r'^.*?-.*?-(.*?)-') AS type
FROM `project.dataset.table`, UNNEST(SPLIT(source_string, ',')) split_col
显然 - 相同的结果
Row name type
1 name1 type1
2 name2 type2
另一种选择是 -
#standardSQL
WITH `project.dataset.table` AS (
SELECT "item1-name1-type1-value1, item2-name2-type2-value2" source_string
)
SELECT
SPLIT(split_col, '-')[SAFE_OFFSET(1)] AS name,
SPLIT(split_col, '-')[SAFE_OFFSET(2)] AS type
FROM `project.dataset.table`, UNNEST(SPLIT(source_string, ',')) split_col
等等...
关于sql - 如何在bigquery中使用正则表达式分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48924455/