使用coalesce返回列名

Lid*_* B. 5 sql postgresql

我想从我的表中的几列中选择第一个非空值.通常我会用

SELECT COALESCE(col1, col2, col3) FROM table
Run Code Online (Sandbox Code Playgroud)

但是这次我不需要值,而是列的名称(或每列的一些指定文本),第一个不是空值.

一个例子:

表:

col1 | col2 | col3
null | null | 3
null | 5    | 8
2    | null | 2
Run Code Online (Sandbox Code Playgroud)

应该返回:

col3
col2
col1
Run Code Online (Sandbox Code Playgroud)

有没有办法用单个SQL语句来做?

注意:我正在使用PostgreSQL.

Nai*_*gun 7

我建议使用CASE声明

SELECT 
   CASE WHEN col1 IS NOT NULL THEN 'col1'
        WHEN col2 IS NOT NULL THEN 'col2'
        WHEN col3 IS NOT NULL THEN 'col3'
        ELSE NULL
   END
FROM table;
Run Code Online (Sandbox Code Playgroud)