BigQuery:压平表格

时间:2018-01-15 22:12:55

标签: google-bigquery

有没有什么方法可以简单地压平下面的表格,这样我就可以将(num * num_2)乘以mul,然后我就可以将id(mul)分组。 所以我真的在寻找类似于下面显示的第二张图像的表格。

Existing table

Expected Output

PS:如果我不再那么结果就像下面所示,这对我想要达到的目标没有帮助 enter image description here

1 个答案:

答案 0 :(得分:2)

以下几个选项(BigQuery Standard SQL)

  
#standardSQL
WITH `yourproject.yourdataset.yourtable` AS (
  SELECT 1 id, [STRUCT<num INT64, num_2 INT64>(2013, 2013),(1625, 1625),(1297, 1297),(7634, 7634)] nums UNION ALL
  SELECT 2, [STRUCT<num INT64, num_2 INT64>(1,1),(2,2),(3,3),(4,4),(5,5)]
)
SELECT id, (SELECT SUM(num * num_2) FROM UNNEST(nums) nums ) as mul
FROM `yourproject.yourdataset.yourtable`   

OR

#standardSQL
WITH `yourproject.yourdataset.yourtable` AS (
  SELECT 1 id, [STRUCT<num INT64, num_2 INT64>(2013, 2013),(1625, 1625),(1297, 1297),(7634, 7634)] nums UNION ALL
  SELECT 2, [STRUCT<num INT64, num_2 INT64>(1,1),(2,2),(3,3),(4,4),(5,5)]
)
SELECT id, SUM(num * num_2) AS mul
FROM `yourproject.yourdataset.yourtable`, UNNEST(nums) nums
GROUP BY id   

都返回

id  mul  
1   66652959     
2   55   

如果您不需要SUM(num * num_2),而只是将表格弄平 - 您可以使用下面的示例

#standardSQL
WITH `yourproject.yourdataset.yourtable` AS (
  SELECT 1 id, [STRUCT<num INT64, num_2 INT64>(2013, 2013),(1625, 1625),(1297, 1297),(7634, 7634)] nums UNION ALL
  SELECT 2, [STRUCT<num INT64, num_2 INT64>(1,1),(2,2),(3,3),(4,4),(5,5)]
)
SELECT id, num, num_2
FROM `yourproject.yourdataset.yourtable`, UNNEST(nums) nums