赞
踩
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;
结果
张三, 李四, 王二, 麻子
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。