Big Query - Trasponi gli array in colonne

Oct 14 2020

Abbiamo una tabella in Big Query come di seguito.

Tabella di input:

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

Vogliamo convertire la tabella sopra nel formato seguente per renderla compatibile con BI / Visualizzazione.

Tabella di destinazione / richiesta:

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

Nota: la colonna Interessi è un tipo di dati array. Questo tipo di trasformazione è possibile in Big Query? Se sì, qualsiasi domanda di riferimento?

Grazie in anticipo!

Risposte

1 MikhailBerlyant Oct 14 2020 at 11:38

Di seguito è per BigQuery Standard SQL e utilizza le funzionalità di scripting di 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
  )
);      

se applicare ai dati campione dalla tua domanda, l'output è