用listagg函数分组实现列转行

来源:这里教程网 时间:2026-03-03 12:55:33 作者:

listagg是Oracle 11.2中新增的函数,listagg可以对order by子句中指定的每个组内的数据进行排序,然后连接这些列的值。以下是简单的应用举例: SELECT deptno, listagg(ename, ',') WITHIN GROUP(ORDER BY ename) AS employees FROM scott.emp GROUP BY deptno; 可以在livesql.oracle.com云平台中体验: 再看以下的查询,包含了重复值: select d.dname, listagg(e.job, ',') within group(order by e.job) jobs from scott.dept d, scott.emp e where d.deptno = e.deptno group by d.dname; Oracle 19C做了一个小改进,可以方便的对转换结果去重,支持distinct关键字: select d.dname, listagg(distinct e.job, ',') within group(order by e.job) jobs from scott.dept d, scott.emp e where d.deptno = e.deptno group by d.dname;

相关推荐