BigQuery - Group by on arrays

前端 未结 1 1082
我在风中等你
我在风中等你 2021-01-29 03:09

I want to group by on an array.

sample query:

#standardSQL
WITH `project.dataset.table` AS (
  SELECT \'compute\' description, \'[{\"key\":\"application         


        
相关标签:
1条回答
  • 2021-01-29 03:28
    #standardSQL
    WITH `project.dataset.table` AS (
      SELECT 'compute' description, '[{"key":"application","value":"scaled-server"},{"key":"department","value":"hrd"}]' labels, 0.323316 cost UNION ALL
      SELECT 'compute' description, '[{"key":"application","value":"scaled-server"},{"key":"department","value":"hrd"}]' labels, 0.342825 cost 
    ), temp AS (
      SELECT description, labels, SUM(cost) AS cost
      FROM `project.dataset.table`
      GROUP BY description, labels
    )
    SELECT 
      description, 
      ARRAY(
        SELECT AS STRUCT 
          JSON_EXTRACT_SCALAR(kv, '$.key') key, 
          JSON_EXTRACT_SCALAR(kv, '$.value') value 
        FROM UNNEST(SPLIT(labels, '},{')) kv_temp, 
        UNNEST([CONCAT('{', REGEXP_REPLACE(kv_temp, r'^\[{|}]$', ''), '}')]) kv
      ) labels,
      cost
    FROM temp
    
    0 讨论(0)
提交回复
热议问题