BigQuery:标准SQL中的NEST替代

时间:2018-10-28 22:13:04

标签: sql google-bigquery data-analysis

标准SQL中NEST函数的替代方法是什么。我已经尝试过像here所述的ARRAY_AGG,但是ARRAY_AGG返回一行,而NEST返回平展的数组。

旧版SQL:NEST Legacy SQL NEST

标准SQL:ARRAY_AGG ARRAY_AGG Standard SQL

2 个答案:

答案 0 :(得分:1)

我有点惊讶,但是这个查询:

select *
from (select 1 as x),
     (select 2 as x),
     (select 3 as x),
     (select 4 as x),
     (select 5 as x)

返回与此查询完全相同的东西:

select *
from (select 1 as x),
     (select 2 as x),
     (select 3 as x),
     (select 4 as x),
     (select 5 as x);

毫无疑问,问题是缺少group by。因此,我认为简单的select *就能满足您的需求:

select *
from (select 1 as x union all select 2 union all select 3 union all select 4 union all select 5
     ) n

答案 1 :(得分:1)

以下是BigQuery:

实际上,标准SQL中的

ARRAY_AGG()与旧版SQL中的NEST()等效
它们都返回一行中的元素数组

区别在于UI如何显示结果重复字段-对于旧版SQL UI,结果将被扁平化,这就是为什么您将其视为“扁平化数组”的原因

您可以通过在下面运行

进行测试
#legacySQL  
SELECT COUNT(1) rows FROM (
  SELECT NEST(x) y
  FROM (SELECT 1 AS x),
    (SELECT 2 AS x),
    (SELECT 3 AS x),
    (SELECT 4 AS x),
    (SELECT 5 AS x)
)

有结果

Row rows     
1   1    

请记住-这样的UI展平仅在大多数外部select语句中发生,并且所有内部select都将NEST视为ARRAYS /重复字段

从将结果保存到表中开始-如果要将以下输出保留为重复字段

#legacySQL  
SELECT NEST(x) y
FROM (SELECT 1 AS x),
  (SELECT 2 AS x),
  (SELECT 3 AS x),
  (SELECT 4 AS x),
  (SELECT 5 AS x)

您需要确保已禁用Flatten Results的{​​{1}}