如何取消嵌套并将所有重复的行写入单行

时间:2019-06-17 08:27:47

标签: google-bigquery

目前,我有一个带有产品名称和成分的嵌套表。但是需要UNNEST()并将所有成分写在一行中。

SELECT productTitle, ingridientTitle  FROM `TABLE`, UNNEST(ingredients)

从这里开始:

productTitle             ingridientTitle
     A                         A
                               C
                               D
                               E

     B
                               A
                               B

     C
                               A
                               C

为此:

productTitle             ingridientTitle
     A                        A,C,D,E
     B                        A,B
     c                        A,C

1 个答案:

答案 0 :(得分:2)

不需要嵌套,可以使用ARRAY_TO_STRING()

with a as (
select 'A' as productTitle
, ['A', 'B' , 'C' , 'D', 'E'] as ingridientTitle 
union all 
select 'B' as productTitle
, ['A', 'B'] as ingridientTitle 
union all 
select 'C' as productTitle
, ['A',  'E'] as ingridientTitle 
)
select productTitle , ARRAY_TO_STRING(ingridientTitle, ",")
from a