大查询或SQL重塑数据

时间:2016-04-17 15:23:28

标签: sql google-bigquery

我将bigquery用于存储数据 例如我有表

userId|event  |count
------------- |
1     |event1 |1
1     |event2 |2
2     |event1 |2
2     |event2 |1 
2     |event3 |4 
3     |event1 |3 
4     |event3 |5 
4     |event4 |5 

我如何获得此表?(在列事件{index}上计算总和) 仅使用能力BigQuery(或SQL)

userId|event1 |event2|event3|event4
----------------------------------
1     |1      |2     |0     |0    |
2     |2      |1     |4     |0    |
3     |0      |0     |0     |0    |
4     |0      |0     |5     |5    |

1 个答案:

答案 0 :(得分:1)

如果您只有少数事件可供您使用 - 您将需要构建与您有不同事件一样多的相应行。如果预期事件的数量不变 - 您可以轻松地构建此类查询一次,然后使用它

SELECT 
  userID,
  SUM(CASE WHEN event = 'event1' THEN [count] ELSE 0 END) AS event1,
  SUM(CASE WHEN event = 'event2' THEN [count] ELSE 0 END) AS event2,
  SUM(CASE WHEN event = 'event3' THEN [count] ELSE 0 END) AS event3,
  SUM(CASE WHEN event = 'event4' THEN [count] ELSE 0 END) AS event4
FROM YourTable
GROUP BY userId

如果您需要更具动感的内容,请查看非常相似的示例https://stackoverflow.com/a/36623258/5221944

在您的情况下,构建动态sql的查询将如下所示

SELECT 'SELECT userId, ' + 
   GROUP_CONCAT_UNQUOTED(
      'SUM(IF(event="'+event+'",[count],0)) as [d_'+REPLACE(event,'/','_')+']'
   ) 
   + ' FROM YourTable GROUP BY userId ORDER BY userId'
FROM (
  SELECT event FROM YourTable GROUP BY event ORDER BY event
)

请注意以下行

      'SUM(IF(event="'+event+'",[count],0)) as [d_'+REPLACE(event,'/','_')+']'

确保您的偶数名称符合字段/列名称的要求 如果你的evens总是看起来像event1,event2等,你可以简化这一行并使用

      'SUM(IF(event = "' + event + '", [count], 0)) as ' + event