Sql Bigquery查询转换表

Sql Bigquery查询转换表,sql,google-bigquery,Sql,Google Bigquery,我有一张这样的桌子: UserID user_properties_key user_properties_value(String) User1 email user_email@gmail.com weight 55 UserId email weight User1 user_email@gmail

我有一张这样的桌子:

UserID    user_properties_key    user_properties_value(String) 
User1      email                     user_email@gmail.com 
           weight                      55   
UserId           email           weight    
User1     user_email@gmail.com     55 
User2     user2_email@email.com    155
我想得到这样的结果:

UserID    user_properties_key    user_properties_value(String) 
User1      email                     user_email@gmail.com 
           weight                      55   
UserId           email           weight    
User1     user_email@gmail.com     55 
User2     user2_email@email.com    155
我当前的查询看起来:

SELECT
  T1.UserId as UserId,
  T1.user_properties_value AS email,
  T2.user_properties_value AS weight,
FROM (FLATTEN([database20160814], user_properties_key )) AS T1
JOIN 
(FLATTEN([database20160814], user_properties_key )) AS T2
ON
  T1.userId = T2.userId
WHERE
  T1.user_properties_key="email"
  AND T2.user_properties_key="weight"
GROUP BY
  V0,
  V1,
  V2

如果我试图获取更多字段,则查询不起作用或需要很长时间,这通常称为透视表操作。前面的问题和答案给出了一个示例:

如果正在使用,则需要更改示例中的某些函数和语法,但原理是相同的。

请尝试下面的内容

SELECT
  UserId,
  MAX(IF(user_properties.user_properties_key="email", user_properties.user_properties_value, NULL)) AS email,
  MAX(IF(user_properties.user_properties_key="weight", user_properties.user_properties_value, NULL)) AS weight
FROM [YourTable] 
GROUP BY UserId

你的问题不清楚,所以我假设你的表格如下


另请参见

谢谢。它起作用了!=)但我有一个问题,一个用户可以有多个值(如何在字段“权重”中生成结果可选(32)或者类似的问题,以及我如何获取此问题的最后一个值。谢谢。请为您的问题添加具体示例,否则我不清楚我是否不断更新数据。我如何获取最后记录的值?我仍然不清楚您的
新问题
到底是什么!我建议您提出新问题,并在那里提供所有相关详细信息。我将非常乐意尝试回答新的问题