有时我们在写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 来分组列,不然就会报错