Big Query - Transpose arrays into colums

主宰稳场 提交于 2021-02-08 06:33:07

问题


We have a table in Big Query like below.

Input table:

 Name | Interests
 -----+----------
 Bob  | ["a"]
 Sue  | ["a","b"]
 Joe  | ["b","c"]

We want to convert the above table to below format to make it BI/Visualisation friendly.

Target/Required table:

 +------------------+
 | Name | a | b | c |
 +------------------+
 | Bob  | 1 | 0 | 0 |
 | Sue  | 1 | 1 | 0 |
 | Joe  | 0 | 1 | 0 |
 +------------------+

Note: The Interests column is an array datatype. Is this sort of transformation possible in Big Query? If yes, Any reference query?

Thanks in advance!


回答1:


Below is for BigQuery Standard SQL and uses scripting features of BQ

#standardSQL
create temp table ttt as (
  select name, interest 
  from `project.dataset.table`, 
  unnest(interests) interest
);

EXECUTE IMMEDIATE (
  SELECT """
  SELECT name, """ || 
    STRING_AGG("""MAX(IF(interest = '""" || interest || """', 1, 0)) AS """ || interest, ', ') 
  || """
  FROM ttt 
  GROUP BY name
  """
  FROM (
    SELECT DISTINCT interest 
    FROM ttt
    ORDER BY interest
  )
);      

if to apply to sample data from your question - output is



来源:https://stackoverflow.com/questions/64346504/big-query-transpose-arrays-into-colums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!