如何找到struct类型数组的总和?

时间:2018-03-07 19:20:19

标签: google-bigquery

如何找到2015年第一季度的总和?

with table1 as(
select [struct("jan" as month,2000 as quantity_sold),("feb",5000),("mar",3000)] as Q1_2015,
 [struct("jan" as month,2050 as quantity_sold),("feb",5100),("mar",3200)]as Q1_2016,
 [struct("jan" as month,3000 as quantity_sold),("feb",4000),("mar",3800)]as Q1_2017)
 ,
table2 as(
select(array(select x from unnest(Q1_2015)x order by quantity_sold desc))as tab2_1
from table1)

select tab2_1, sum(tab2_1.quantity_sold)   from table2;

我有以下错误

Error: Cannot access field quantity_sold on a value with type ARRAY<STRUCT<month STRING, quantity_sold INT64>> at [10:19]

1 个答案:

答案 0 :(得分:1)

首先 - 如果没有GROUP BY您的最终SELECT将无效 - 并且会因以下内容而失败

Error: SELECT list expression references column tab2_1 which is neither grouped nor aggregated  

同时,使用以下错误解决当前问题:

Error: Cannot access field quantity_sold on a value with type ARRAY<STRUCT<month STRING, quantity_sold INT64>> at [10:19]    

你应该使用类似下面的内容

   
#standardSQL
WITH table1 AS(
  SELECT 
    [STRUCT("jan" AS month,2000 AS quantity_sold),("feb",5000),("mar",3000)] AS Q1_2015,
    [STRUCT("jan" AS month,2050 AS quantity_sold),("feb",5100),("mar",3200)]AS Q1_2016,
    [STRUCT("jan" AS month,3000 AS quantity_sold),("feb",4000),("mar",3800)]AS Q1_2017
), table2 AS(
SELECT
  (ARRAY(SELECT x FROM UNNEST(Q1_2015) x ORDER BY quantity_sold DESC)) AS tab2_1
  FROM table1
)
SELECT SUM(tab2_1[OFFSET(0)].quantity_sold)   
FROM table2    

上面只是解决了您提出的错误问题 - 其余的逻辑与您的问题完全一致,我认为结果不符合您的预期 - 很可能只是您的“旅程”的开始

无论如何 - 要产生三个月的总和 - 请在下面使用

#standardSQL
WITH table1 AS(
  SELECT 
    [STRUCT("jan" AS month,2000 AS quantity_sold),("feb",5000),("mar",3000)] AS Q1_2015,
    [STRUCT("jan" AS month,2050 AS quantity_sold),("feb",5100),("mar",3200)]AS Q1_2016,
    [STRUCT("jan" AS month,3000 AS quantity_sold),("feb",4000),("mar",3800)]AS Q1_2017
), table2 AS(
SELECT
  (SELECT SUM(quantity_sold) FROM UNNEST(Q1_2015)) AS total_sold
  FROM table1
)
SELECT total_sold   
FROM table2    

我认为这个问题已得到解答 - 请将任何新问题发布为“新问题”