oralce将多行合并一行(列转行) listagg()函数

本文详细介绍了Oracle的LISTAGG函数,一种用于将多行数据合并为一行的实用工具,适用于Oracle11及更高版本。LISTAGG函数不仅能够按指定顺序排序并连接列值,还可用作分析函数,实现复杂的数据聚合需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值