任何容忍NULL值的CONCAT()变体?

时间:2017-04-14 23:02:50

标签: sql google-bigquery

当任何值为NULL时,CONCAT()返回NULL。我必须使用IFNULL()来 包装传递给CONCAT()的所有字段。是否存在CONCAT()变体 忽略NULL?

例如:

#standardSQL
WITH data AS (
  SELECT 'a' a, 'b' b, CAST(null AS STRING) nu
)

SELECT CONCAT(a, b, nu) concatenated, ARRAY_TO_STRING([a,b,nu], ',') w_array_to_string
FROM `data`

--->
null

2 个答案:

答案 0 :(得分:3)

快速Jam Session有趣的主题

这里可能无限组合现实生活用例 以下是一些变化:

  
#standardSQL
WITH data AS (
  SELECT 'a' a, 'b' b, 'c' c UNION ALL
  SELECT 'y', 'x', NULL UNION ALL
  SELECT 'v', NULL, 'w'
)
SELECT 
  *,
  CONCAT(a, b, c) by_concat, 
  ARRAY_TO_STRING([a,b,c], '') by_array_to_string,
  ARRAY_TO_STRING([a,b,c], '', '?') with_null_placeholder,
  ARRAY_TO_STRING(
    (SELECT ARRAY_AGG(col ORDER BY col DESC) 
      FROM UNNEST([a,b,c]) AS col 
      WHERE NOT col IS NULL)
    , '') with_order
FROM `data`  

输出结果为:

a   b       c       by_concat   by_array_to_string  with_null_placeholder   with_order   
-   ----    ----    ---------   ------------------  ---------------------   ----------
y   x       null    null        yx                  yx?                     yx   
a   b       c       abc         abc                 abc                     cba  
v   null    w       null        vw                  v?w                     wv   

答案 1 :(得分:1)

改为使用ARRAY_TO_STRING([col1,col2,...]):

#standardSQL
WITH data AS (
  SELECT 'a' a, 'b' b, CAST(null AS STRING) nu
)

SELECT ARRAY_TO_STRING([a,b,nu], '') w_array_to_string
FROM `data`

--->
ab