假设我有以下模式:
[
{
'name': 'id',
'type': 'INTEGER'
}
{
'name': 'record',
'type': 'RECORD',
'fields': [
{
'name': 'repeated',
'type': 'STRING',
'mode': 'REPEATED'
}
]
}
]
以及以下数据:
+--------------------+
|id |record.repeated|
+--------------------+
|1 |'a' |
| |'b' |
| |'c' |
+--------------------+
|2 |'a' |
| |'c' |
+--------------------+
|3 |'d' |
+--------------------+
我需要创建一个返回以下内容的查询:
+--------------------+
|id |record.repeated|
+--------------------+
|1 |'a,b,c' |
+--------------------+
|2 |'a,c' |
+--------------------+
|3 |'d' |
+--------------------+
换句话说,我需要查询允许我使用分隔符(在本例中为逗号)连接嵌套字段的值。类似于 MySQL 的 GROUP_CONCAT 函数,但在 BigQuery 上。
相关思路:Concat sql中所有列值
这可能吗?
谢谢。
非常简单
select group_concat(record.repeated) from table
来自公共数据的一个例子是
SELECT group_concat(payload.shas.encoded)
FROM [publicdata:samples.github_nested]
WHERE repository.url='https://github.com/dreamerslab/workspace'
对于标准sql:
select id, string_agg(record.field)
from your_table, unnest(record)
或
select id, string_agg(record.field)
from your_table left join unnest(record)
WITH
t AS (
SELECT
'1' AS a,
'2' AS b)
SELECT
ARRAY_TO_STRING([a, b], ',')
FROM
t
对 REPEATED 记录进行 LEFT JOIN,然后使用 STRING_AGG 和 DISTINCT,如下所示:
SELECT ol.RecordId, STRING_AGG(DISTINCT pmt.method," | ") AS PaymentType
FROM `my-dw.my-dataset.order_item` roi
LEFT JOIN UNNEST(order_line) ol
LEFT JOIN UNNEST(detail.payment) pmt
GROUP BY 1
LIMIT 100
整个记录可以重复(即嵌套或节点)或者是“节点中的节点”。该示例显示了两者。