How to unnest and pivot two columns in BigQuery

前端 未结 3 1203
谎友^
谎友^ 2021-01-27 07:40

Say I have a BQ table containing the following information

| id    | test.name     | test.score    |
|----   |-----------    |------------   |
| 1     | a                 


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-27 08:22

    Conditional aggregation is a good approach. If your tables are large, you might find that this has the best performance:

    select t.id,
           (select max(tt.score) from unnest(t.score) tt where tt.name = 'a') as a,
           (select max(tt.score) from unnest(t.score) tt where tt.name = 'b') as b,
           (select max(tt.score) from unnest(t.score) tt where tt.name = 'c') as c
    from `table` t;
    

    The reason I recommend this is because it avoids the outer aggregation. The unnest() happens without shuffling the data around -- and I have found that this is a big win in terms of performance.

提交回复
热议问题