2016-11-23 94 views
2

我想要生成一個新表,並使用BigQuery將所有帶鍵的鍵值對作爲列名和值作爲它們各自的值。在BigQuery(Pivot實現)中將行轉換爲列

例子:

**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辦呢?

回答

4

的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

+0

這是卓有成效的。 – Prabhjot