skytf=> create table city (country character varying(64),city character varying(64));
CREATE TABLE skytf=> insert into city values ('中国','台北');
INSERT 0 1
skytf=> insert into city values ('中国','香港');
INSERT 0 1
skytf=> insert into city values ('中国','上海');
INSERT 0 1
skytf=> insert into city values ('日本','东京');
INSERT 0 1
skytf=> insert into city values ('日本','大阪');
INSERT 0 1
skytf=> select * From city;
country | city
---------+------
中国 | 台北
中国 | 香港
中国 | 上海
日本 | 东京
日本 | 大阪
(5 rows)
一 方法一:使用聚集函数 array_agg
--1.1 函数说明
Function name array_agg
Argument Type(s) any
Return Type array of the argument type
Description input values, including nulls, concatenated into an array
--1.2 测试函数
skytf=> \df array_agg
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+-----------+------------------+---------------------+------
pg_catalog | array_agg | anyarray | anyelement | agg
(1 row) skytf=> select country,array_agg(city) from city group by country;
country | array_agg
---------+------------------
中国 | {台北,香港,上海}
日本 | {东京,大阪}
(2 rows)
备注: 这正是我们需要的结果,返回的结果类型为数组。
二 方法二:使用聚集函数 string_agg
--2.1函数说明
Function name string_agg(expression, delimiter)
Argument Type(s) text, text
Return Type text
Description input values concatenated into a string, separated by delimiter
--2.2 测试函数
skytf=> select country,string_agg(city,',') from city group by country;
country | string_agg
---------+----------------
中国 | 台北,香港,上海
日本 | 东京,大阪
(2 rows) skytf=> select country,string_agg(city,',') from city where country='中国' group by country;
country | string_agg
---------+----------------
中国 | 台北,香港,上海
(1 row)
--3.2 测试函数
skytf=> select country,array_accum(city) from city where country='中国' group by country;
country | array_accum
---------+------------------
中国 | {台北,香港,上海}
(1 row)
备注:同样得到了预期的结果,返回的类型为数组。