如何在BigQuery中将含NULL的字符串列转换为无NULL元素的数组
解决数组包含NULL元素的报错问题
直接用[A,B,C]生成数组时,只要列中有NULL值,数组就会包含NULL元素,触发Array cannot have a null element报错。要生成仅包含非NULL值的数组,不同SQL引擎可以用以下方法:
方法1:Spark SQL / BigQuery
使用array_remove函数直接移除数组中的NULL元素:
select array_remove([A,B,C], NULL) as tags from table
这个函数会自动过滤掉数组里的所有NULL值,正好匹配需求——哪个列是NULL就自动排除,剩下的非NULL值组成数组。
方法2:PostgreSQL
通过unnest展开数组后过滤NULL,再重新聚合为数组:
select array(select elem from unnest(array[A,B,C]) elem where elem is not null) as tags from table
方法3:Hive SQL
结合lateral view explode展开数组,过滤NULL后用collect_list重新聚合:
select collect_list(elem) as tags from your_table lateral view explode(array(A,B,C)) tmp as elem where elem is not null group by id -- 替换为原表中需要保留的主键或其他列
内容的提问来源于stack exchange,提问作者p.magalhaes
相关产品推荐
相关产品推荐

