我有 3 列(名字、中间名、姓氏),我想连接 3 个字符串(以构建全名)。
但是,如果这些值中有任何一个为 null,则结果为 null。
当其中一些字符串可能为空时,连接字符串的优雅且安全的方法是什么?
NVL()
/IFNULL()
和CONCAT_WS()
的组合也可以,但我更喜欢以下:
select array_to_string(array_construct_compact(column1, column2, column3), ' ')
from values('a', 'b', 'c'), ('a', null, 'c')
array_construct_compact()
删除空值。array_to_string()
在连接时添加必要的空格。https://docs.snowflake.com/en/sql-reference/functions/array_construct_compact.html
我无法让上面的数组示例与连接列名称的别名一起使用。
但是,单独使用
IFNULL
效果很好,例如:
> SELECT CONCAT
> (
> IFNULL(FIRST_NAME,''),' ',
> IFNULL(MIDDLE_NAME,''),' ',
> IFNULL(SURNAME,''),' '
> ) AS "Full Name"
https://docs.snowflake.com/en/sql-reference/functions/concat
https://docs.snowflake.com/en/sql-reference/functions/ifnull