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

问题描述 投票:1回答:1

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

我有这张桌子:

+------+------+------+--------+--------+--------+
| 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中拼出所有列。我如何通过循环实现这一目标?

sql postgresql database-design concatenation dynamic-sql
1个回答
0
投票

除了可疑的数据库设计,您可以动态生成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 tbl;'
FROM   pg_attribute
WHERE  attrelid = 'tbl'::regclass
AND    attnum > 0
AND    NOT attisdropped;

db <>小提琴here

在第二步中执行(确认它是您想要的之后。)>

不涉及循环。我没有针对可能的NULL值建立防御。您可能想要也可能不想添加。

查询系统目录pg_attribute或信息模式表pg_attribute。我更喜欢系统目录。

  • columns
  • columns很方便,但是它忽略NULL值。确定您要如何处理这些问题。相关:

© www.soinside.com 2019 - 2024. All rights reserved.