Big Query - transpor objetos array / json em colunas
Oct 21 2020
Esta pergunta é uma continuação dessas duas:
- Big Query - Transponha matrizes em colunas
- Big Query - Transpor campos específicos para colunas
Temos uma tabela no Big Query como abaixo.
Tabela de entrada:
Name | Question | Answer
-----+-----------+-------
Bob | Interest | ["a"]
Sue | Interest | ["a", "b"]
Joe | Interest | ["b"]
Joe | Gender | Male
Bob | Gender | Female
Sue | DOB | 2020-10-17
Bob | Others | { "country" : "es", "language" : "ca"}
Observação: todos os valores na coluna Resposta são valores stringificados e os objetos Arrays / JSON são dinâmicos.
Queremos converter a tabela acima para o formato abaixo para torná-la amigável para BI / Visualização.
Tabela desejada:
+-------------------------------------------------------------+
| Name | a | b | c | Gender | DOB | country | language |
+-------------------------------------------------------------+
| Bob | 1 | 0 | 0 | Female | 2020-10-17 | es | ca |
| Sue | 1 | 1 | 0 | - | - | - | - |
| Joe | 0 | 1 | 0 | Male | - | - | - |
+-------------------------------------------------------------+
Respostas
2 MikhailBerlyant Oct 21 2020 at 11:38
Abaixo está o BigQuery Standard SQL
#standardSQL
create temp table data as
select name, question, value as answer
from `project.dataset.table`,
unnest(split(translate(answer, '[]" ', ''))) value
where question = 'Interest'
union all
select name, question, answer
from `project.dataset.table`
where not question in ('Interest', 'Others')
union all
select name,
split(value, ':')[offset(0)] as question,
split(value, ':')[offset(1)] as answer
from `project.dataset.table`,
unnest(split(translate(answer, '{}" ', ''))) value
where question = 'Others';
EXECUTE IMMEDIATE (
SELECT """
SELECT name, """ || STRING_AGG("""MAX(IF(answer = '""" || value || """', 1, 0)) AS """ || value, ', ')
FROM (
SELECT DISTINCT answer value FROM data
WHERE question = 'Interest' ORDER BY value
)) || (
SELECT ", " || STRING_AGG("""MAX(IF(question = '""" || value || """', answer, '-')) AS """ || value, ', ')
FROM (
SELECT DISTINCT question value FROM data
WHERE question != 'Interest' ORDER BY value
)) || """
FROM data
GROUP BY name
""";
se aplicar a dados de amostra de sua pergunta
with `project.dataset.table` AS (
select 'Bob' name, 'Interest' question, '["a"]' answer union all
select 'Sue', 'Interest', '["a", "b"]' union all
select 'Joe', 'Interest', '["b"]' union all
select 'Joe', 'Gender', 'Male' union all
select 'Bob', 'Gender', 'Female' union all
select 'Sue', 'DOB', '2020-10-17' union all
select 'Bob', 'Others', '{ "country" : "es", "language" : "ca"}'
)
a saída é
Nota: EXECUTE IMMEDIATEparte do script acima é exatamente o mesmo da postagem anterior - a mudança é apenas na preparação dos dados originais na tabela temporária datae em vez de usá-los naEXECUTE IMMEDIATE
O que significa um erro “Não é possível encontrar o símbolo” ou “Não é possível resolver o símbolo”?
George Harrison ficou chateado por suas letras de 'Hurdy Gurdy Man' de Donovan não terem sido usadas