当前位置:   article > 正文

PostgreSQL:string_agg 多列值聚合成一列_pgsql string_agg

pgsql string_agg

PostgreSQL:string_agg 多列值聚合成一列

string_agg是PostgreSQL中的一个聚合函数,用于将一组值连接为一个字符串。它接受两个参数:要连接的值和连接符。

语法如下:

string_agg(expression, delimiter)
  • 1

其中,expression是要连接的值的表达式,可以是列名、常量或表达式;delimiter是用于分隔连接的字符串。

string_agg通常结合GROUP BY子句一起使用,以便将结果按组连接到一列中。

下面是一个示例:

SELECT string_agg(name, ', ') AS concatenated_names
FROM employee;
  • 1
  • 2

该查询将连接employee表中所有员工的姓名,并使用逗号分隔。结果将在一列中显示。

请注意,使用string_agg函数时,要注意连接后的字符串可能会超过数据库中设置的字符串长度限制。如果需要,可以使用substring函数截断结果字符串以满足长度要求。

示例

create table employee(
    id int4 primary key,
    name varchar(100)
);

comment on table employee is '职工表';
comment on column employee.name is '职工名';

insert into employee(id,name) values (1,'张三');
insert into employee(id,name) values (2,'李四');
insert into employee(id,name) values (3,'王二');
insert into employee(id,name) values (4,'麻子');


select string_agg(name,', ') as concatenated_names
from employee;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

结果 张三, 李四, 王二, 麻子

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/470188
推荐阅读
相关标签
  

闽ICP备14008679号