我已经在BigQuery中执行了以下代码
SELECT ( --inner query
SELECT STRING_AGG(c) FROM t1.array_column c
)
FROM (
select 1 as f1, ['1','2','3'] as array_column
union all
select 2 as f1, ['5','6','7'] as array_column
) t1;
我期望类似
Row|f0_
1 | 1,2,3,4,5,6,7
因为内部查询中没有GROUP BY
。因此,我希望STRING_AGG
会在所有行中得到评估。
SELECT STRING_AGG(c) FROM t1.array_column c
相反,我得到的是这样的东西:
Row|f0_
1 |1,2,3
2 |5,6,7
我很难理解为什么会有这个结果
答案 0 :(得分:2)
以下是用于BigQuery标准SQL
#standardSQL
SELECT STRING_AGG((SELECT STRING_AGG(c) FROM t1.array_column c))
FROM (
SELECT 1 AS f1, ['1','2','3'] AS array_column UNION ALL
SELECT 2 AS f1, ['5','6','7'] AS array_column
) t1
产生
Row f0_
1 1,2,3,5,6,7
注1:您几乎就在那儿–您只是缺少了额外的STRING_AGG
来完成根据每行各自数组创建的字符串的最终分组
注2:由于array_column
是数组类型,因此被视为引用为t1.array_column
的内部表,因此-FROM t1.array_column c
等效于FROM UNNEST(array_column) c
-非常酷{ {1}}功能:o)
答案 1 :(得分:1)
这是您的查询:
SELECT (SELECT STRING_AGG(c) FROM t1.array_column c
)
FROM (select 1 as f1, ['1', '2', '3'] as array_column
union all
select 2 as f1, ['5', '6', '7'] as array_column
) t1;
首先,我很惊讶它能起作用。我以为您需要unnest()
:
SELECT (SELECT STRING_AGG(c) FROM UNNEST(t1.array_column) c
)
发生了什么事?好吧,如果您选择f1
,这将更加明显。然后您将得到:
1 1,2,3
2 5,6,7
这应该使它更清楚。对于t1
中的每一行(有两行),您的代码为:
c
的列将数组取消嵌套成行。如果要合并数组中的元素,请使用array_concat_agg()
:
SELECT array_concat_agg(array_column)
FROM (select 1 as f1, ['1','2','3'] as array_column
union all
select 2 as f1, ['5','6','7'] as array_column
) t1;
如果要将其表示为字符串而不是数组,请使用array_to_string()
:
SELECT array_to_string(array_concat_agg(array_column), ',')
FROM (select 1 as f1, ['1','2','3'] as array_column
union all
select 2 as f1, ['5','6','7'] as array_column
) t1;