类别:

条件表达式函数

COALESCE

返回其实参中的第一个非 NULL 表达式;如果其所有实参都是 NULL,则返回 NULL。

语法

COALESCE( <expr1> , <expr2> [ , ... , <exprN> ] )
Copy

使用说明

  • Snowflake 对实参执行 隐式转换 以使其兼容。例如,如果其中一个输入表达式是数值类型,则返回类型也是数值类型。也就是说,SELECT COALESCE('17', 1); 首先将 VARCHAR 值 '17' 转换为 NUMBER 值 17,然后返回第一个非 NULL 的值。

    当无法进行转换时,隐式转换将失败。例如,SELECT COALESCE('foo', 1); 返回错误,因为 VARCHAR 值 'foo' 无法转换为 NUMBER 值。

    We recommend passing in arguments of the same type or explicitly converting arguments if needed.

  • 当隐式转换将非数值转换为数值时,结果为 NUMBER(18,5) 类型的值。

    对于不是常量的数值字符串实参,如果 NUMBER(18,5) 不足以表示数值,则将实参 转换 为可以表示该值的类型。

排序规则详细信息

  • The collation specifications of all input arguments must be compatible.

  • The comparisons follow the collation based on the input arguments' collations and precedences.

  • The collation of the result of the function is the highest-precedence collation of the inputs.

示例

以下示例显示了三列中的值,以及将 COALESCE 函数应用于这三列后的结果:

SELECT column1,
       column2,
       column3,
       COALESCE(column1, column2, column3) AS coalesce_result
  FROM (values
    (1,    2,    3   ),
    (null, 2,    3   ),
    (null, null, 3   ),
    (null, null, null),
    (1,    null, 3   ),
    (1,    null, null),
    (1,    2,    null)
  ) v;
Copy
+---------+---------+---------+-----------------+
| COLUMN1 | COLUMN2 | COLUMN3 | COALESCE_RESULT |
|---------+---------+---------+-----------------|
|       1 |       2 |       3 |               1 |
|    NULL |       2 |       3 |               2 |
|    NULL |    NULL |       3 |               3 |
|    NULL |    NULL |    NULL |            NULL |
|       1 |    NULL |       3 |               1 |
|       1 |    NULL |    NULL |               1 |
|       1 |       2 |    NULL |               1 |
+---------+---------+---------+-----------------+
语言: 中文