PostgreSQL 多行变一行

前端之家收集整理的这篇文章主要介绍了PostgreSQL 多行变一行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

实例表:

postgres=# \d book2
                              Table "public.book2"
 Column |       Type        |                     Modifiers                      
--------+-------------------+----------------------------------------------------
 id     | integer           | not null default nextval('book2_id_seq'::regclass)
 name   | character varying | 
 tag    | character varying |
postgres=# select * from book2;
 id | name | tag 
----+------+-----
  1 | java | aa
  1 | java | bb
  1 | java | cc
  2 | C++  | dd
  2 | C++  | ee
(5 rows)
需要的效果
 name | string_agg 
------+------------
 C++  | dd,ee
 java | aa,bb,cc
(2 rows)


方法1:string_agg(字段名,分隔符)
postgres=# select name,string_agg(tag,',') from book2 group by name;
 name | string_agg 
------+------------
 C++  | dd,cc
(2 rows)


方法2:array_agg(字段名)

postgres=# select name,array_agg(tag) from tb3 group by name;
 name | array_agg  
------+------------
 c++  | {dd,ee}
 java | {aa,cc}
(2 rows)<strong>

</strong>postgres=# select name,array_to_string(array_agg(tag),') from tb3 group by name;
 name | array_to_string 
------+-----------------
 c++  | dd,cc
(2 rows)

猜你在找的Postgre SQL相关文章