在BigQuery中将行转换为列(Pivot实现)

时间:2016-11-23 10:11:49

标签: sql google-bigquery google-cloud-platform

我想生成一个新表,并使用BigQuery将所有键值对作为列名和值作为各自的值放置。

示例:

**Key**                  **Value**
channel_title           Mahendra Guru    
youtube_id              ugEGMG4-MdA  
channel_id              UCiDKcjKocimAO1tV    
examId                  72975611-4a5e-11e5   
postId                  1189e340-b08f 

channel_title           Ab Live  
youtube_id              3TNbtTwLY0U  
channel_id              UCODeKM_D6JLf8jJt    
examId                  72975611-4a5e-11e5   
postId                  0c3e6590-afeb

我想将其转换为:

**channel_title   youtube_id   channel_id         examId               postId**
Mahendra Guru   ugEGMG4-MdA  UCiDKcjKocimAO1tV  72975611-4a5e-11e5   1189e340-b08f
Ab Live         3TNbtTwLY0U  UCODeKM_D6JLf8jJt  72975611-4a5e-11e5   0c3e6590-afeb

如何使用BigQuery做到这一点?

1 个答案:

答案 0 :(得分:12)

BigQuery不支持旋转功能
您仍然可以使用以下方法在BigQuery中执行此操作

但首先,除了输入数据中的两列之外,还必须有一列可以指定输入中需要在输出中组合成一行的行组

所以,我假设您的输入表(yourTable)如下所示

**id**  **Key**                  **Value**
   1    channel_title           Mahendra Guru    
   1    youtube_id              ugEGMG4-MdA  
   1    channel_id              UCiDKcjKocimAO1tV    
   1    examId                  72975611-4a5e-11e5   
   1    postId                  1189e340-b08f 

   2    channel_title           Ab Live  
   2    youtube_id              3TNbtTwLY0U  
   2    channel_id              UCODeKM_D6JLf8jJt    
   2    examId                  72975611-4a5e-11e5   
   2    postId                  0c3e6590-afeb  

所以,首先你应该运行以下查询

SELECT 'SELECT id, ' + 
   GROUP_CONCAT_UNQUOTED(
      'MAX(IF(key = "' + key + '", value, NULL)) as [' + key + ']'
   ) 
   + ' FROM yourTable GROUP BY id ORDER BY id'
FROM (
  SELECT key 
  FROM yourTable
  GROUP BY key
  ORDER BY key
) 

上述查询的结果将是字符串(如果要格式化)将如下所示

SELECT 
  id, 
  MAX(IF(key = "channel_id", value, NULL)) AS [channel_id],
  MAX(IF(key = "channel_title", value, NULL)) AS [channel_title],
  MAX(IF(key = "examId", value, NULL)) AS [examId],
  MAX(IF(key = "postId", value, NULL)) AS [postId],
  MAX(IF(key = "youtube_id", value, NULL)) AS [youtube_id] 
FROM yourTable 
GROUP BY id 
ORDER BY id

你现在应该复制上面的结果(注意:你真的不需要格式化它 - 我只是为了呈现它)并将其作为普通查询运行

结果将如你所料

id  channel_id          channel_title   examId              postId          youtube_id   
1   UCiDKcjKocimAO1tV   Mahendra Guru   72975611-4a5e-11e5  1189e340-b08f   ugEGMG4-MdA  
2   UCODeKM_D6JLf8jJt   Ab Live         72975611-4a5e-11e5  0c3e6590-afeb   3TNbtTwLY0U  

请注意:如果您可以自己构建正确的查询(如步骤2)并且字段数量小且不变或者是一次性交易,则可以跳过步骤1。但是第1步只是帮助你的步骤,所以你可以随时快速创建它!

  

如果您有兴趣 - 可以在我的其他帖子中看到有关旋转的更多信息。

How to scale Pivoting in BigQuery?
请注意 - 每张桌子有10K列的限制 - 所以你受限于10K组织 您还可以在下面看到简化示例(如果上面的一个太复杂/冗长):
How to transpose rows to columns with large amount of the data in BigQuery/SQL?
How to create dummy variable columns for thousands of categories in Google BigQuery?
Pivot Repeated fields in BigQuery

相关问题