在postgresql中将行转换为字符串

时间:2014-02-03 11:22:38

标签: sql postgresql postgresql-9.3

表名为t1。字段名称为name1。 name1有这样的值

-------------------------------------------+
+       name1                              +
--------------------------------------------
|    "a_2013,AcMaster,Master"              |
|   "b_2014,AcMaster,Master"               |
|   "c_2013,a_AcMaster,a_Master"           |
|    "d_2014,a_AcMaster,a_Master"          |
|__________________________________________|

但我想像这样得到重新开始

  master          acmaster               text
   Master          AcMaster                a_2013,b_2014
   a_Master        a_Master                c_2013,d_2014

所以我试试这个

    select (string_to_array(schemaname,',')) [3] as master,(string_to_array(schemaname,','))
 [2] as acmaster,(string_to_array(schemaname,',')) [1] from appsetup.company2 
c2,appsetup.company1 c1,appsetup.companygroup cg where    c1.compno=c2.compno and 
cg.compgroupno=c1.compgroupno and c1.compno in (3,2) group by 
string_to_array(schemaname,',')) [3],
(string_to_array(schemaname,',')) [2],cg.compgroupno,schemaname order by 
cg.compgroupno

但它的回归

master          acmaster               text
   Master          AcMaster              ["a_2013","b_2014"]
   a_Master        a_Master              ["c_2013","d_2014"]

如何获得我想要的结果?

使用 Postgresql 9.3

1 个答案:

答案 0 :(得分:19)

你可以试试这个:

select string_agg(name1, ',') as Name1s
from t1

string_agg