Oracle函数之LISTAGG
最近在学习的过程中,发现⼀个挺有意思的函数,它可实现对列值的拼接。下⾯我们来看看其具体⽤法。
⽤法:
对其作⽤,官⽅⽂档的解释如下:
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的⽤法如下:
下⾯对该函数进⾏举例说明:
普通函数,对⼯资进⾏排序,⽤逗号进⾏拼接。
SQL> 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
分组函数:
SQL> 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
分析函数:
SQL> 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
values什么意思30 ALLEN 1600 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE
30 BLAKE 2850 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE
14 rows selected.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论