Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big Query or SQL reshape data

im use bigquery for storage data For example im have table

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 

How i can get this table?(on column event{index} count sum) using only ability BigQuery(or 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    |
like image 734
ivan Avatar asked Oct 30 '22 05:10

ivan


1 Answers

If you have just few events below will work for you - you will need to construct as many respective rows as you have different events. If number of expected events constant - you can always easily build such query once and then use it

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

If you need something more dynamic - look at very similar example https://stackoverflow.com/a/36623258/5221944

In your case that query to build dynamic sql will look as below

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
)

Note below line

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

It makes sure your even name complies with requirement for fields/columns name
If your evens will always look like event1, event2, etc you can simplify this line and use

      'SUM(IF(event = "' + event + '", [count], 0)) as ' + event
like image 81
Mikhail Berlyant Avatar answered Nov 11 '22 18:11

Mikhail Berlyant