Postgres:获取跨列的最大长度



我正在尝试检索一个长度最大的记录。

我有一张这样的桌子:

ID | Column1    | Column2      | Column3
--------------------------------------------
1  |   123456   |   1234       |   12     
2  |   123      |   1234567    |   NULL

我想要这样的输出:

ID | Column1    | Column2      | Column3  | Max_Column
---------------------------------------------------------
1  |   123456   |   1234       |   12     |  123456
2  |   123      |   1234567    |   NULL   |  1234567

在这种情况下,通过使用CASE语句可以很容易地实现它。但在原始表格中,我有20多列。

我尝试使用INFORMATION_SCHEMA.COLUMNS表,但它并没有多大帮助,因为它仅限于一列。我希望查询解析一行中的所有列,并返回具有MAX LENGTH的列。

您可以使用横向连接:

select t.*, v.max_col
from t cross join lateral
(select max(col) as max_col
from (values (col1), (col2), . . . ) v(col)
) v;

如果愿意,可以使用information_schema.columns和SQL语句生成代码,也可以将列名复制到电子表格中并在那里生成代码。

或者你可以使用Postgres的非标准greatest()函数:

select t.*, greatest(col1, col2, . . .) as max_col
from t;

最新更新