postgresql:字符串求和(拼接)

解决方案:

1.将table转换为array

2.借助array_to_string将array进行拼接

 

示例:

--创建测试表
DROP TABLE IF EXISTS test;
CREATE TEMP TABLE test("Id" int,"Name" varchar(100),"Type" int);
INSERT INTO test("Id","Name","Type")VALUES(1,'NO1',1),(2,'NO2',2),(3,'NO3',2),(4,'NO4',2),(5,'NO5',3),(6,'NO6',3);

--将结果转换为数组
--SELECT array(SELECT "Name" FROM test)

--将数组合并为字符串
--select array_to_string(array[1,2,3], ',')

--合并后的结果
--SELECT array_to_string(array(SELECT "Name" FROM test), ',')

SELECT "Type" ,( array_to_string(array(SELECT "Name" FROM test as t WHERE t."Type" = test."Type" ) , ',') )  FROM test GROUP BY "Type";

DROP TABLE test;


 

posted @ 2017-07-17 12:18  zhao379028604  阅读(12886)  评论(0编辑  收藏  举报