不按顺序合并

Coalesce with no preference to order

我有 3 列要移动到 1。在每一行中,将只填充 3 列中的 1 列。例如:

**col1 | col2 | col3**  
 10    | null | null  
 null  | 15   | null  
 null  | null | 9  
 22    | null | null  
 null  | 2    | null  
 17    | null | null  

我现在想将所有列合并为一个。
首先,这是最好的方法吗?

其次,有没有办法指定 COALESCE() 参数的顺序是否重要?

编辑:最终结果应为:

col1  
----  
10  
15  
9  
22  
2  
17

试试这个:

SELECT (SELECT MAX(v) 
        FROM (VALUES (col1), (col2), (col3)) AS x(v))
FROM mytable        

上述查询使用 Table Value Constructor 来构建包含所有三个 table 列的内联 table。在此 table return 上应用 MAX 非空值。

Demo here

编辑:

看来您可以通过简单地使用 COALESCE:

来获得所需的结果
SELECT COALESCE(col1, col2, col3) AS col
FROM mytable 

COALESCE 表达式将 return 第一个 非空字段的值。