【问题标题】:BigQuery - Concatenate multiple columns into a single column for large numbers of columnsBigQuery - 将多列连接成一列以获取大量列
【发布时间】:2021-01-12 17:48:54
【问题描述】:

我的数据看起来像:

row col1 col2 col3 ... coln
1 A null B ... null
2 null B C ... D
3 null null null ... A

我想将列压缩在一起得到:

row final
1 A, B
2 B, C, D
3 A

字母的顺序无关紧要,如果解决方案包含空值,例如。 A,null,B,null 等。我可以研究如何稍后删除它们。我已经用完了 coln,因为我有大约 200 列要压缩。

我已经尝试了一些方法,如果我想压缩行,我可以使用 STRING_AGG() example

另外我可以这样做:

SELECT 
CONCAT(col1,", ",col2,", ",col3,", ",coln) #ect.
 FROM mytable

但是,这将涉及手动写出每个列名,这是不可行的。有没有更好的方法可以理想地为整个表实现这一目标。

另外,如果任何值为 NULL,CONCAT 会返回 NULL。

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:
    #standardSQL
    select row, 
      (select string_agg(col, ', ' order by offset)
      from unnest(split(trim(format('%t', (select as struct t.* except(row))), '()'), ', ')) col with offset
      where not upper(col) = 'NULL'
      ) as final
    from `project.dataset.table` t    
    

    如果应用于您问题中的样本数据 - 输出是

    【讨论】:

      【解决方案2】:

      与您要求的格式不完全一致,但如果这样可以简化您的操作,您可以尝试:

      SELECT TO_JSON_STRING(mytable) FROM mytable
      

      如果您想要确切的格式,您可以编写一个正则表达式来从输出的 JSON 字符串中提取值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-13
        • 2023-02-25
        • 1970-01-01
        • 2017-06-19
        • 1970-01-01
        • 2018-08-14
        • 1970-01-01
        • 2012-01-01
        相关资源
        最近更新 更多