« PostgreSQL 基础:如何查看 PostgreSQL 中SQL的执行计划 | Blog首页 | Oracle 20c 新特性:原生的区块链支持 Native Blockchain tables »
PostgreSQL 基础:行列转换实现类MySQL的 group_concat 功能
链接:https://www.eygle.com/archives/2019/09/postgresql_group.html
在数据库开发和查询中,我们经常需要进行行列转换,将具有一定相同属性的数据进行聚合展示。任何数据库都是一致的。
在 MySQL中存在一个函数 : Group_Concat 可以用于实现类似的功能。
mysql> select error_code,group_concat(db_version order by db_version) from oracode
where error_code='ORA-04031' group by error_code;
+------------+----------------------------------------------+
| error_code | group_concat(db_version order by db_version) |
+------------+----------------------------------------------+
| ORA-04031 | 10g,11g,12c |
+------------+----------------------------------------------+
1 row in set (0.01 sec)
在 PostgreSQL 中,可以通过 array_to_string 进行转换:
enmotech=# select error_code,array_to_string(array_agg(db_version),',') from oracode
where error_code='ORA-04031' group by error_code;
error_code | array_to_string
------------+-----------------
ORA-04031 | 11g,19c
(1 row)
在 Oracle 数据库中,曾经可以通过 wm_concat 进行转换(不再推荐这个方法),但是现在已经被 LISTAGG 替代。
SQL> select wmsys.wm_concat(username) from dba_users;
WMSYS.WM_CONCAT(USERNAME)
--------------------------------------------------------------------------------
SYS,SYSTEM,YANGTK,TEST,OUTLN,MGMT_VIEW,FLOWS_FILES,MDSYS,ORDSYS,EXFSYS,DBSNMP,WM
SELECT deptno,
LISTAGG(ename, ',') WITHIN GROUP(ORDER BY ename) AS employees
FROM scott.emp GROUP BY deptno;
DEPTNO EMPLOYEES
10 CLARK,KING,MILLER
20 ADAMS,FORD,JONES,SCOTT,SMITH
30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD
参考连接:
https://www.eygle.com/archives/2012/10/wmsys_wm_concat.html
https://www.enmotech.com/web/detail/1/641/2.html
历史上的今天...
>> 2018-09-16文章:
>> 2010-09-16文章:
>> 2009-09-16文章:
>> 2008-09-16文章:
>> 2007-09-16文章:
>> 2005-09-16文章:
>> 2004-09-16文章:
By eygle on 2019-09-16 10:07 | Comments (0) | FAQ | 3362 |