Quantcast
Channel: MogDB Life
Viewing all articles
Browse latest Browse all 353

PostgreSQL 基础:行列转换实现类MySQL的 group_concat 功能

$
0
0

作者:eygle 发布在 eygle.com

在数据库开发和查询中,我们经常需要进行行列转换,将具有一定相同属性的数据进行聚合展示。任何数据库都是一致的。

group_concat.jpg

在 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

相关文章|Related Articles


Viewing all articles
Browse latest Browse all 353

Trending Articles