简体   繁体   中英

Google Big Query array aggregation with sum

SQL beginner here.

WITH vals AS
  (
    SELECT 1 x, 'a' y, 120 z UNION ALL
    SELECT 1 x, 'a' y, 359 z UNION ALL
    SELECT 1 x, 'b' y, 130 z UNION ALL
    SELECT 2 x, 'a' y, 140 z UNION ALL
    SELECT 2 x, 'c' y, 160 z
  )
SELECT x, ARRAY_AGG(y) as array_aggy,  ARRAY_AGG(z) as array_aggz
FROM vals
GROUP BY x;

The output of this query is

Row     x         array_aggy    array_aggz  
1       1             a            120
                      a            359
                      b            130

2       2             a            140
                      c            160

I want to sum array_aggz values if they have the same value in array_aggy

Row     x         array_aggy    array_aggz  
1       1             a            479
                      b            130

2       2             a            140
                      c            160

Use below

select x, array_agg(y) as array_aggy,  array_agg(aggz) as array_aggz
from (
  select x, y, sum(z) aggz
  from vals
  group by x, y    
)
group by x             

with output

在此处输入图像描述

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