oralce將多行合併一行(列轉行) listagg()函數

        有時我們在寫sql語句時可能會遇到將多行數據合併成一行的情況,那麼這是就可以用這個listagg()函數,listagg()函數是Oracle的列轉行函數,但是要注意只有是Oracle11以上版本才支持。

用法:

對其作用,官方文檔的解釋如下:

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:分隔符,默認爲NULL

order_by_clause:order by子句決定了列值被拼接的順序。

通過該用法,可以看出LISTAGG函數不僅可作爲一個普通函數使用,也可作爲分析函數。

order_by_clause和query_partition_clause的用法如下:

基本語法規則:

listagg(列名,' 分割符號') within group(order by 列值被拼接的順序)

分組函數:

用法1:

    select distinct st.student_id,st.student_name,
    LISTAGG(p.persion_name,',') within group(order by p.persion_id) over (partition by p.persion_id) persion_name,

    LISTAGG(p.persion_groud,',') within group(order by p.persion_id) over (partition by p.persion_id) persion_groud
    from student st, persion p
    where st.student_id= p.student_id;

用法2:

    select st.student_id,st.student_name,
    LISTAGG((p.persion_name,',') within group(order by p.persion_id) persion_name,
    LISTAGG(p.persion_groud,',') within group(order by p.persion_id) ) persion_groud
    from student st, persion p
    where st.student_id= p.student_id;

   group by st.student_id,st.student_name

partition by 查出的結果集是重複的,需要使用 distinct 進行顯式去重. 而用第二中用法,那麼必須要使用group by 來分組列,不然就會報錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章