How to unnest and pivot two columns in BigQuery

前端 未结 3 1231
谎友^
谎友^ 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:18

    Below is generic/dynamic way to handle your case

    EXECUTE IMMEDIATE (
      SELECT """
      SELECT id, """ || 
        STRING_AGG("""MAX(IF(name = '""" || name || """', score, NULL)) AS """ || name, ', ') 
      || """
      FROM `project.dataset.table` t, t.test
      GROUP BY id
      """
      FROM (
        SELECT DISTINCT name
        FROM `project.dataset.table` t, t.test
        ORDER BY name
      )
    );  
    

    If to apply to sample data from your question - output is

    Row     id      a       b       c    
    1       1       5       7       null     
    2       2       8       null    3    
    

提交回复
热议问题