如何使用循环连接数据列?

How to concat data columns using loop?

如何在 Postgres 中使用循环连接列数据?

我有这个table:

+------+------+------+--------+--------+--------+
| col1 | col2 | col3 | other1 | other2 | other3 |
+------+------+------+--------+--------+--------+
|    1 |    1 |    1 |      1 |      1 |      1 |
|    2 |    2 |    2 |      2 |      2 |      2 |
+------+------+------+--------+--------+--------+

并想要连接列 (col*)。

预期输出:

+----------------+--------+--------+--------+
| concatedcolumn | other1 | other2 | other3 |
+----------------+--------+--------+--------+
| **1**1**1**    |      1 |      1 |      1 |
| **2**2**2**    |      2 |      2 |      2 |
+----------------+--------+--------+--------+

我可以使用以下方式连接:

select concat('**', col1, '**',col2, '**', col3, '**') as concatedcolumn
      ,other1, other2, other3
from sample_table

我有大约 200 个前缀为 "col" 的列,不想拼出 sql 中的所有列。我如何通过循环实现此目的?

抛开有问题的数据库设计,您可以动态生成 SELECT 语句:

SELECT 'SELECT concat_ws(''**'', '
     || string_agg(quote_ident(attname), ', ') FILTER (WHERE attname LIKE 'col%')
     || ') AS concat_col, '
     || string_agg(quote_ident(attname), ', ') FILTER (WHERE attname NOT LIKE 'col%')
     || ' FROM public.tbl;'                  -- your table name here
FROM   pg_attribute
WHERE  attrelid = 'public.tbl'::regclass     -- ... and here
AND    attnum > 0
AND    NOT attisdropped;

db<>fiddle here

查询系统目录pg_attribute or, alternatively, the information schema table columns。我更喜欢系统目录。

第二步执行(确认是你想要的之后)。

不涉及循环。您可以动态构建语句,但您不能(轻松地)return动态结果,因为 SQL 需要知道return 在执行时输入。

concat_ws() 很方便,但它会忽略 NULL 值。我没有专门处理那些。你可能想也可能不想那样做。相关:

  • Combine two columns and add into one new column
  • How to concatenate columns in a Postgres SELECT?