PostgreSQL:string_agg 多列值聚合成一列

PostgreSQL:string_agg 多列值聚合成一列

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

语法如下:

string_agg(expression, delimiter)

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

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

下面是一个示例:

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

该查询将连接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;

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

你可能感兴趣的:(postgreSQL,postgresql,数据库)