2

它可实现对列值的拼接。下面我们来看看其具体用法。

对其作用,官方文档的解释如下:

For a specified measure, LISTAGG orders data within each group specified in the ORDER BY clause and then concatenates the values of the measure column.

即在每个分组内,LISTAGG根据order by子句对列植进行排序,将排序后的结果拼接起来。

measure\_expr:可以是任何基于列的表达式。
delimiter:分隔符,默认为NUL
order\_by\_clause:order by子句决定了列值被拼接的顺序。

通过该用法,可以看出LISTAGG函数不仅可作为一个普通函数使用,也可作为分析函数。

order\_by\_clause和query\_partition\_clause的用法如下:

下面对该函数进行举例说明:
普通函数,对工资进行排序,用逗号进行拼接。

 select listagg(ename,',')within group(order by sal)name    from emp;

结果:

NAME
----------------------------------------------------------------------------------------------------
SMITH,JAMES,ADAMS,MARTIN,WARD,MILLER,TURNER,ALLEN,CLARK,BLAKE,JONES,FORD,SCOTT,KING

+groupby分组函数:

 select deptno,listagg(ename,',')within group(order by sal)name from emp group by deptno;

结果:

    DEPTNO NAME 
    10     MILLER,CLARK,KING 
    20     SMITH,ADAMS,JONES,FORD,SCOTT 
    30     JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE

+over(partition by )分析函数:

select deptno,ename,sal,listagg(ename,',')within group(order by sal)over(partition by deptno)name from emp;

结果:


    DEPTNO ENAME             SAL NAME  
    10     MILLER           1300 MILLER,CLARK,KING 
    10     CLARK            2450 MILLER,CLARK,KING 
    10     KING             5000 MILLER,CLARK,KING 
    20     SMITH             800 SMITH,ADAMS,JONES,SCOTT,FORD       
    20     ADAMS            1100 SMITH,ADAMS,JONES,SCOTT,FORD       
    20     JONES            2975 SMITH,ADAMS,JONES,SCOTT,FORD       
    20     SCOTT            3000 SMITH,ADAMS,JONES,SCOTT,FORD       
    20     FORD             3000 SMITH,ADAMS,JONES,SCOTT,FORD       
    30     JAMES             950 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 
    30     MARTIN           1250 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 
    30     WARD             1250 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 
    30     TURNER           1500 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 
    30     ALLEN            1600 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 
    30     BLAKE            2850 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 

注意: Oracle 11g 没有配置这个函数


参考素材:
1.oracle的 listagg() WITHIN GROUP () 行转列函数的使用
2.Oracle 11g 新聚集函数listagg实现列转行


蜗牛
27 声望13 粉丝