【问题标题】:How to pivot array build from REGEXP_EXTRACT_ALL如何从 REGEXP_EXTRACT_ALL 旋转数组构建
【发布时间】:2021-06-29 18:32:01
【问题描述】:

我正在 BigQuery 表中收集带有查询参数的 url。我想解析这些 url,然后旋转表格。最后输入数据和预期输出。

我找到了两个要合并的查询。

这个用来旋转我解析的网址:

select id, 
       max(case when test.name='a' then test.score end) as a,
       max(case when test.name='b' then test.score end) as b,
       max(case when test.name='c' then test.score end) as c
from 
(
select a.id, t
from `table` as a,
unnest(test) as t
)A group by id

然后我有这个查询来解析 url:

WITH examples AS (
  SELECT 1   AS id, 
  '?foo=bar' AS query, 
  'simple'   AS description
  UNION ALL SELECT 2, '?foo=bar&bar=baz', 'multiple params'
  UNION ALL SELECT 3, '?foo[]=bar&foo[]=baz', 'arrays'
  UNION ALL SELECT 4, '', 'no query'
)
SELECT 
  id, 
  query,
  REGEXP_EXTRACT_ALL(query,r'(?:\?|&)((?:[^=]+)=(?:[^&]*))') as params,
  REGEXP_EXTRACT_ALL(query,r'(?:\?|&)(?:([^=]+)=(?:[^&]*))') as keys,
  REGEXP_EXTRACT_ALL(query,r'(?:\?|&)(?:(?:[^=]+)=([^&]*))') as values,
  description
FROM examples

我不确定要解释我的问题。但我认为这是因为当我将查询参数拆分为单独的列时,它与我需要 merge 同一列下的键和值的第一个查询的格式不匹配,因此我可以正确地取消嵌套它们.

输入数据:

| id    | url                   |
|----   |--------------------   |
| 1     | url/?foo=aaa&bar=ccc  |
| 2     | url/?foo=bbb&bar=ccc  |

预期输出:

| id    | foo  | bar |
|----   |----  |---- |
| 1     | aaa  | ccc |
| 2     | bbb  | ccc |

我的参数数量完全相同

【问题讨论】:

标签: sql google-bigquery pivot flatten unnest


【解决方案1】:

在下面使用

select id, 
  max(if(split(kv, '=')[offset(0)] = 'foo', split(kv, '=')[offset(1)], null)) as foo,
  max(if(split(kv, '=')[offset(0)] = 'bar', split(kv, '=')[offset(1)], null)) as bar
from `project.dataset.table` t, 
unnest(regexp_extract_all(url, r'[?&](\w+=\w+)')) kv
group by id            

如果应用于您问题中的样本数据 - 输出是

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多