PostgreSQL中的group_concat使用

group_concat是mysql中的一個彙集函數,挺好用的,mysql的group_concat使用可參考:http://my.oschina.net/Kenyon/blog/70480。在postgresql中實現這個功能倒也容易,能夠用array的轉換或者函數string_agg()來作。

DB環境:postgresql 9.1.2

一.測試數據準備
postgres=# create table t_kenyon(id int,name text);
CREATE TABLE
postgres=# insert into t_kenyon values(1,'kenyon'),(1,'chinese'),(1,'china'),('2','american'),('3','japan'),('3','russian');
INSERT 0 6
postgres=# select * from t_kenyon order by 1;
 id |   name   
----+----------
  1 | kenyon
  1 | chinese
  1 | china
  2 | american
  3 | japan
  3 | russian
(6 rows)
二.實現過程

1.以逗號爲分隔符彙集
postgres=# select array_to_string(ARRAY(SELECT unnest(array_agg(name))),',') from t_kenyon ;
               array_to_string               
---------------------------------------------
 kenyon,chinese,china,american,japan,russian
(1 row)

 2.結合order by排序
postgres=# select array_to_string(ARRAY(SELECT unnest(array_agg(name)) order by 1),',') from t_kenyon;
               array_to_string               
---------------------------------------------
 american,china,chinese,japan,kenyon,russian
(1 row)

 3.結合group彙集
postgres=# SELECT id, array_to_string(ARRAY(SELECT unnest(array_agg(name)) 
             ),',') FROM t_kenyon GROUP BY id;
 id |   array_to_string    
----+----------------------
  1 | china,chinese,kenyon
  2 | american
  3 | japan,russian
(3 rows)
4.以其餘分隔符彙集,如*_*
postgres=# SELECT id, array_to_string(ARRAY(SELECT unnest(array_agg(name)) 
             order by 1),'*_*') FROM t_kenyon GROUP BY id ORDER BY id;
 id |     array_to_string      
----+--------------------------
  1 | china*_*chinese*_*kenyon
  2 | american
  3 | japan*_*russian
(3 rows)


還有一個函數更簡:string_agg
mysql

postgres=# create table t_test(id int,vv varchar(100)); 
CREATE TABLE 
postgres=# insert into t_test values(1,'kk'),(2,'ddd'),(1,'yy'),(3,'ty'); 
INSERT 0 4  

postgres=# select * from t_test;  
id | vv   
----+-----   
1 | kk   
2 | ddd   
1 | yy   
3 | ty 
(4 rows)  

postgres=# select id,string_agg(vv,'*^*') from t_test group by id;  
id | string_agg  
----+------------   
1 | kk*^*yy   
2 | ddd   
3 | ty 
(3 rows) 



三.總結

postgresql也能夠很簡單的實現mysql中的group_concat功能,並且更加豐富,能夠基於此寫一個同名的函數。 sql

相關文章
相關標籤/搜索