简体   繁体   中英

Grouping repeated fields in BQ

I have the following table where "product" is a repeated field.

在此处输入图像描述

How can I group by "id" and merge the repeated field to sum the quantities so the output looks like this.

在此处输入图像描述

Trying to find an elegant solution that does not unnest.

Consider below

select id, array(
  select as struct sku, sum(quantity) quantity
  from t.product
  group by sku
  ) product
from (
  select id, array_concat_agg(product) product
  from your_table
  group by id
) t          

if applied to sample data in your question - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM