SQL concat函数和concat_ws函数的区别

发布时间 2023-06-14 23:18:27作者: ttttttian

总结

相同点:都是将几个字符串拼接在一起的函数
异同点:

  1. 拼接的字符串中有null值时,返回结果不一样
  2. 参数代表的含义不一样。concat中的参数都是要拼接的,concat_ws的第一个参数是分隔符,后面才是要拼接的

concat函数

是将数据集的几个列拼接成一列。

concat(col1, col2, ..., colN) - Returns the concatenation of col1, col2, ..., colN.
https://spark.apache.org/docs/latest/api/sql/#concat
但是当某一列的值为null值时,即便其他列有值,那么也会返回null值。

SELECT concat("A", null ) from input1  


那么如果,想忽略null值,返回有值的部分,可以加一个coalesce函数:

SELECT concat("A", coalesce(null,"") ) from input1 

concat_ws函数

作用也是将数据集的几个列拼接成一列,但是可以一次性指定分隔符。第一个参数位置是指定的分隔符,之后的位置是要拼接的列。

concat_ws(sep[, str | array(str)]+) - Returns the concatenation of the strings separated by sep.
https://spark.apache.org/docs/latest/api/sql/#concat_ws
当某一列的值为null值时,concat_ws会跳过null值

SELECT concat_ws(",", "A", "B", "C", null) from input1  


ps: 分隔符为null时,返回null。

所以:
当要拼接的列中有null值时,可以用
1. concat("A", coalesce(null,"") )
2. concat_ws(",", "A", "B", "C", null)。 适用于一次性指定分隔符
3. concat("", "A", "-", "B", ",", "C", null), 适用于分隔符是不一样的