BigQuery - 连接忽略 NULL

BigQuery - concatenate ignoring NULL

我对 SQL 很陌生。我知道 MySQL 中有 CONCAT_WS 函数,但是 BigQuery 不识别这个。

我有一堆二十个字段需要连接成一个逗号分隔的字符串,但有些是 NULL,如果一个是 NULL,那么整个结果将是 NULL。这是我目前所拥有的:

CONCAT(m.track1, ", ", m.track2))) As Tracks,

我试过了,但它也是 returns NULL:

CONCAT(m.track1, IFNULL(m.track2,CONCAT(", ", m.track2))) As Tracks,

非常感谢任何建议,提前谢谢。

很遗憾,BigQuery 不支持 concat_ws()。因此,一种方法是 string_agg():

select t.*,
       (select string_agg(track, ',')
        from (select t.track1 as track union all select t.track2) x
       ) x
from t;

实际上更简单的方法是使用数组:

select t.*,
       array_to_string([track1, track2], ',')

结果集中不支持具有 NULL 值的数组,但它们可用于中间结果。

I have a bunch of twenty fields I need to CONCAT into one comma-separated string

假设这些是 table 中唯一的字段 - 您可以使用以下方法 - 足够通用以处理任意数量的列及其名称 w/o 显式枚举

select  
  (select string_agg(col, ', ' order by offset)
  from unnest(split(trim(format('%t', (select as struct t.*)), '()'), ', ')) col with offset
  where not upper(col) = 'NULL'
  ) as Tracks
from `project.dataset.table` t

下面是一个过于简单的虚拟示例来尝试,测试方法

#standardSQL
with `project.dataset.table` as (
  select 1 track1, 2 track2, 3 track3, 4 track4 union all
  select 5, null, 7, 8
)
select  
  (select string_agg(col, ', ' order by offset)
  from unnest(split(trim(format('%t', (select as struct t.*)), '()'), ', ')) col with offset
  where not upper(col) = 'NULL'
  ) as Tracks
from `project.dataset.table` t    

有输出