1. 程式人生 > >PostgreSql 聚合函式string_agg與array_agg 相當於mysql group_concat

PostgreSql 聚合函式string_agg與array_agg 相當於mysql group_concat

array_agg(expression)
把表示式變成一個數組 一般配合 array_to_string() 函式使用
  • 1
  • 2
string_agg(expression, delimiter)
直接把一個表示式變成字串
  • 1
  • 2

案例:

create table(empno smallint, ename varchar(20), job varchar(20), mgr smallint, hiredate date, sal bigint, comm bigint, deptno smallint);

insert into jinbo.employee(empno,ename,job, mgr, hiredate, sal, comm, deptno) values
(7499, 'ALLEN', 'SALEMAN', 7698, '2014-11-12', 16000, 300, 30);
insert into jinbo.employee(empno,ename,job, mgr, hiredate, sal, comm, deptno) values (7499, 'ALLEN', 'SALEMAN', 7698, '2014-11-12', 16000, 300, 30); insert into jinbo.employee(empno,ename,job, mgr, hiredate, sal, comm, deptno) values (7654, 'MARTIN'
, 'SALEMAN', 7698, '2016-09-12', 12000, 1400, 30);
select * from jinbo.employee; empno | ename | job | mgr | hiredate | sal | comm | deptno -------+--------+---------+------+------------+-------+------+-------- 7499 | ALLEN | SALEMAN | 7698 | 2014-11-12 | 16000 | 300 | 30 7566 | JONES | MANAGER | 7839 | 2015-12-12 | 32000 | 0 | 20 7654 | MARTIN | SALEMAN | 7698 | 2016-09-12 | 12000 | 1400 | 30 (3 rows)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

1.查詢同一個部門下的員工且合併起來

方法1:
select deptno, string_agg(ename, ',') from jinbo.employee group by deptno;

 deptno |  string_agg  
--------+--------------
     20 | JONES
     30 | ALLEN,MARTIN

方法2:
select deptno, array_to_string(array_agg(ename),',') from jinbo.employee group by deptno;
 deptno | array_to_string 
--------+-----------------
     20 | JONES
     30 | ALLEN,MARTIN
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2、在1條件的基礎上,按ename 倒敘合併

select deptno, string_agg(ename, ',' order by ename desc) from jinbo.employee group by deptno;
 deptno |  string_agg  
--------+--------------
     20 | JONES
     30 | MARTIN,ALLEN
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3、按陣列格式輸出使用 array_agg

select deptno, array_agg(ename) from jinbo.employee group by deptno;
 deptno |   array_agg    
--------+----------------
     20 | {JONES}
     30 | {ALLEN,MARTIN}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4、array_agg 去重元素,例如查詢所有的部門

select array_agg(distinct deptno) from jinbo.employee;
array_agg 
-----------
 {20,30}
(1 row)

#不僅可以去重,還可以排序

select array_agg(distinct deptno order by deptno desc) from jinbo.employee;
 array_agg 
-----------
 {30,20}
(1 row)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13