旋转重复字段BigQuery

时间:2015-11-17 22:39:02

标签: google-bigquery

我的架构看起来像这样:

userid:string
timestamp:integer
params:nested/repeated field with 2 fields
  - name:string (possible values: "a", "b","c")
  - value:string

我希望我的查询返回以下内容:

userid, timestamp, a, b, c
123, 1447799796, foo, bar, xyz
233, 1447799900, bob, xxx, yyy
:
:

最简单的方法是什么?

2 个答案:

答案 0 :(得分:2)

当可能的值事先知道并且没有那么多可以手动编写SQL时 - 您可以在下面使用:

SELECT 
  userid,
  ts,
  MAX(IF(params.name = "a", params.value, NULL)) WITHIN RECORD a,
  MAX(IF(params.name = "b", params.value, NULL)) WITHIN RECORD b,
  MAX(IF(params.name = "c", params.value, NULL)) WITHIN RECORD c
FROM yourTable 

如果可能的值提前“未知”和/或从运行到运行是动态的,则可以使用下面的帮助程序SQL生成上述类型的SQL。

SELECT 'select userid, ts, ' + 
   GROUP_CONCAT_UNQUOTED(
      'max(if(params.name = "' + STRING(params.name) + '", params.value, null)) 
       WITHIN RECORD as [' + STRING(params.name) + ']'
   ) 
   + ' from yourTable '
FROM (SELECT params.name FROM yourTable GROUP BY params.name)

答案 1 :(得分:1)

这些方面的东西:

SELECT 
  userid,
  timestamp,
  FIRST(name == "a", value, NULL) WITHIN RECORD a,
  FIRST(name == "b", value, NULL) WITHIN RECORD b,
  FIRST(name == "c", value, NULL) WITHIN RECORD c,
FROM t