Search code examples
google-bigquerytransposeunpivotunnest

GBQ Unpviot Columns into single column and multiple rows


Hi All Trying to figure out a similar solution to a previous question but slightly different solution. I am trying to figure out a way to unpivot a varying number of columns and have the results be in one column

Input This would be a sql table (tbl_fruit) that exists as the image depicts

SELECT * FROM tbl_fruit

enter image description here

Output

enter image description here

Potential Solution Per the linked question I am trying to rework that solution but keep having errors

select `Group`, split(kv, ':')[offset(0)] output
from tbl_fruit t,
unnest((select as struct t.* except(`Group`))) kv
where kv[offset(1)] != '0'
group by `Group`

Solution

  • select `Group`, split(kv, ':')[offset(0)] output
    from `project.dataset.table` t,
    unnest(split(translate(to_json_string((select as struct t.* except(`Group`))), '{}"', ''))) kv
    where split(kv, ':')[offset(1)] != '0'    
    

    with output

    enter image description here