BigQuery 中的透视转换:将行转置为列
问题:
目标是在 BigQuery 中将数据从行转换为列,其中键变为列名称和值成为对应的列值。
示例:
之前:
Key | Value |
---|---|
channel_title | Mahendra Guru |
youtube_id | ugEGMG4-MdA |
examId | 72975611-4a5e-11e5 |
channel_id | UCiDKcjKocimAO1tV |
postId | 1189e340-b08f |
之后:
channel_title | youtube_id | channel_id | examId | postId |
---|---|---|---|---|
Mahendra Guru | ugEGMG4-MdA | UCiDKcjKocimAO1tV | 72975611-4a5e-11e5 | 1189e340-b08f |
解决方案:
当前的 BigQuery缺乏本机旋转功能。但是,以下方法可以达到相同的结果:
步骤 1:生成查询结构
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 )
步骤 2:运行查询和转换
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
注意事项:
以上是如何在 BigQuery 中将行转换为列?的详细内容。更多信息请关注PHP中文网其他相关文章!