PostgreSQL如何实现MySQL中的group_concat聚集函数(简单的拼接功能)

1.postgreSQL中没有现成的group_concat聚集函数
2.postgreSQL可以自定义聚集函数
group_concat和group by一起使用,group_concat函数返回一个字符串结果,该结果由分组中的值连接组合而成。

SELECT id, group_concat(city) from cities group by id

id     group_concat(city)
---------------------------
1      {'上海'}       
2      {'南京','北京'}

group_concat()参数anyelement匹配任何类型,聚集后返回数组类型anyarray,该函数的功能是将每行的记录附加到数组里。
SELECT country, group_concat(name) from city group by country

group_concat(name)为数组类型,再用array_to_string函数将数组转换为字符串
SELECT country, array_to_string(group_concat(name),',') from city group by country




原文地址:https://www.cnblogs.com/xingmangdieyi110/p/11738707.html