eygle.com   eygle.com
eygle.com eygle
eygle.com  
 

« PostgreSQL 基础:如何查看 PostgreSQL 中SQL的执行计划 | Blog首页 | Oracle 20c 新特性:原生的区块链支持 Native Blockchain tables »

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

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

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


历史上的今天...
    >> 2018-09-16文章:
    >> 2010-09-16文章:
    >> 2009-09-16文章:
    >> 2008-09-16文章:
    >> 2007-09-16文章:
    >> 2005-09-16文章:
           Tom's New book has landed
    >> 2004-09-16文章:

By eygle on 2019-09-16 10:07 | Comments (0) | FAQ | 3362 |


CopyRight © 2004~2020 云和恩墨,成就未来!, All rights reserved.
数据恢复·紧急救援·性能优化 云和恩墨 24x7 热线电话:400-600-8755 业务咨询:010-59007017-7040 or 7037 业务合作: marketing@enmotech.com