Dynamically creating columns from row data using Select in Bigquery

后端 未结 1 546
后悔当初
后悔当初 2021-01-15 07:55

Background

I want to rename my case statement in sql select statement dynamically.

Eg:

SELECT (case when id= x.id then x.sums

相关标签:
1条回答
  • 2021-01-15 08:19

    Below is for BigQuery!

    Please note: your expectations about output column names are not correct!
    Column name cannot start with digit - so in below example - i will be using id_1, id_2 and id_3 instead of 1, 2 and 3

    SELECT
      SUM(CASE WHEN id = 1 THEN 1 END) AS id_1,
      SUM(CASE WHEN id = 2 THEN 1 END) AS id_2,
      SUM(CASE WHEN id = 3 THEN 1 END) AS id_3
    FROM YourTable
    

    Above example assumes you know in advance your IDs and there are very few of them so it is not a big deal to write manually few numbers of lines with SUM(...) for each id

    If this is not a case - you can first generate above query programmatically by running below query

    SELECT 'SELECT ' + 
       GROUP_CONCAT_UNQUOTED(
          'SUM(CASE WHEN id = ' + STRING(id) + ' THEN 1 END) AS id_' + STRING(id)
       ) 
       + ' FROM YourTable'
    FROM (
      SELECT id FROM (
        SELECT * FROM YourTable GROUP BY id ORDER BY id
    )
    

    as a result - you will get string like below

    SELECT SUM(CASE WHEN id = 1 THEN 1 END) AS id_1,SUM(CASE WHEN id = 2 THEN 1 END) AS id_2,SUM(CASE WHEN id = 3 THEN 1 END) AS id_3 FROM YourTable
    

    So, now just copy it and paste into Query Editor and run it

    you can see similar example here - https://stackoverflow.com/a/36623258/5221944

    0 讨论(0)
提交回复
热议问题