最近在學習的過程中,發現一個挺有意思的函數,它可實現對列值的拼接。下面我們來看看其具體用法。
用法:
對其作用,官方文檔的解釋如下:
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 30 ALLEN 1600 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 30 BLAKE 2850 JAMES,MARTIN,WARD,TURNER,ALLEN,BLAKE 14 rows selected.