在BigQuery中将Long table转换为宽表

时间:2020-06-22 15:11:57

标签: google-bigquery

我有一个这样的BigQuery表:

enter image description here

必需的输出是:

enter image description here

注意::Extended_property_key列中的键不是固定的,它会不断增加。因此,“输出”中的列也将继续添加。

我需要构建一个Bigquery,它可以处理与旋转相关的输出查询中列的动态添加。

2 个答案:

答案 0 :(得分:2)

以下是用于BigQuery标准SQL

'r+'

如果应用于问题中的样本数据-输出为

EXECUTE IMMEDIATE '''
SELECT account_id, ''' || (
  SELECT STRING_AGG(DISTINCT "MAX(IF(Extended_property_key = '" || Extended_property_key || "', Extended_property_value, NULL)) AS " || Extended_property_key)
  FROM `project.dataset.table`
) || '''  
FROM `project.dataset.table`
GROUP BY 1
ORDER BY 1
'''   

答案 1 :(得分:1)

尝试:

CALL fhoffa.x.pivot(
  'p.d.t1' # source table
  , 'p.d.t2' # destination table
  , ['ACCOUNT_ID'] # row_ids
  , 'EXTENDED_PROPERTY_KEY' # pivot_col_name
  , 'EXTENDED_PROPERTY_VALUE' # pivot_col_value
  , 30 # max_columns
  , 'ANY_VALUE' # aggregation
  , '' # optional_limit
);

有关如何旋转的更多详细信息:

相关问题