【问题标题】:How to aggregate multiple rows into one in BigQuery?如何在 BigQuery 中将多行聚合为一行?
【发布时间】:2016-03-04 06:10:21
【问题描述】:

假设您有一个包含多行的非规范化架构,如下所示:

   uuid    |    property    |    value   
------------------------------------------
  abc      |   first_name   |  John
  abc      |   last_name    |  Connor
  abc      |   age          |  26
...

所有行的属性集相同,不一定要排序。 如何使用 BigQuery 等创建表(即无客户端):

表用户属性:

   uuid    |    first_name  |    last_name   |    age
 --------------------------------------------------------
  abc      |   John         |    Connor      |    26

在传统 SQL 中,为此目的存在“STUFF”关键字。

如果我至少可以得到按 uuid 排序的结果,这样客户端就不需要加载整个表 (4GB) 来进行排序,这样就可以对每个表进行水合实体通过顺序扫描具有相同 uuid 的行。但是,这样的查询:

SELECT * FROM user_properties ORDER BY uuid; 

超出 BigQuery 中的可用资源(使用 allowLargeResults 禁止 ORDER BY)。除非我订阅高端机器,否则我似乎无法在 BigQuery 中对大表(4GB)进行排序。有什么想法吗?

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:
    SELECT 
      uuid,
      MAX(IF(property = 'first_name', value, NULL)) AS first_name,
      MAX(IF(property = 'last_name', value, NULL)) AS last_name,
      MAX(IF(property = 'age', value, NULL)) AS age
    FROM user_properties
    GROUP BY uuid
    

    另一种选择 - 不涉及 GROUP'ing

    SELECT uuid, first_name, last_name, age  
    FROM (
      SELECT 
        uuid,
        LEAD(value, 1) OVER(PARTITION BY uuid ORDER BY property) AS first_name,
        LEAD(value, 2) OVER(PARTITION BY uuid ORDER BY property) AS last_name,
        value AS age,
        property = 'age' AS anchor
      FROM user_properties
    )
    HAVING anchor
    

    【讨论】:

    • 当我尝试在查询中使用相同的技术时,我得到了SELECT list expression references column flow_timestamp which is neither grouped nor aggregated at [1:8]SELECT flow_timestamp, MAX(IF(channel_properties.key = 'number_of_digits', channel_properties.value, NULL)) AS number_of_digits FROM my_table , unnest(timeseries.channel_properties) as channel_properties是因为channel_properties是嵌套字段吗?
    • @Yang - 是的。将您的问题发布为新问题,我会跟进答案
    • 当然,会检查它:o)
    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 2013-12-13
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多