oracle listagg函数

LISTAGG 函数介绍

listagg 函数是 Oracle 11.2 推出的新特性。
其主要功能类似于 wmsys.wm_concat 函数, 即将数据分组后, 把指定列的数据再通过指定符号合并。

函数作用:分组后根据条件将不同列的字段合并到同一列

LISTAGG 使用

listagg 函数有两个参数:
		1、 要合并的列名
		2、 自定义连接符号

☆LISTAGG 函数既是分析函数,也是聚合函数
所以,它有两种用法:
		1、分析函数,如: row_number()、rank()、dense_rank() 等,用法相似
		listagg(合并字段, 连接符) within group(order by 合并的字段的排序) over(partition by 分组字段)
		2、聚合函数,如:sum()、count()、avg()等,用法相似
		listagg(合并字段, 连接符) within group(order by 合并字段排序)		--后面跟 group by 语句


(补充)分析函数和聚合函数

一部分聚合函数其实也可以写成分析函数的形式。

分析函数和聚合函数本质上都是对数据进行分组,二者最大的不同便是:
	对数据进行分组分组之后,
	聚合函数只会每组返回一条数据,
	而分析函数会针对每条记录都返回,
		一部分分析函数还会对同一组中的数据进行一些处理(比如:rank() 函数对每组中的数据进行编号);
		还有一部分分析函数不会对同一组中的数据进行处理(比如:sum()、listagg()),这种情况下,分析函数返回的数据会有重复的,distinct 处理之后的结果与对应的聚合函数返回的结果一致。

 

测试:

-- 执行成功 查询各物业区域的负责人和职务信息(将姓名和职务两个字段合并到同一列) 记录数:7134
select area,listagg(to_char(name)||'-'||to_char(detail),',') within group(order by detail asc), count(1)
from ACC_PERSONS group by area

 

--执行失败 因为分组了两次 当使用group by分组后 就不需要 over (partition by xx)
select area, count(1), listagg(to_char(name)||'-'||to_char(detail),',') within group(order by detail asc) over (partition by area)
from ACC_PERSONS group by area


-- 执行成功 记录数:14639 数量比上面多是因为没有进行分组聚合 如果同一个物业区域下有7条数据则有7条记录 上面的根据分组函数将7条数据合并为了1条记录
select area, listagg(to_char(name)||'-'||to_char(detail),',') within group(order by detail asc) over (partition by area)
from ACC_PERSONS

 

--多分组

select count(1), area ,detail, listagg(to_char(name)||'-',',') within group(order by area asc, detail asc),
listagg(to_char(tags)||'-'||to_char(typecode),',') within group(order by area asc, detail asc)
from acc_persons where area is not null group by area, detail order by area asc ;

 

select area,detail, listagg(to_char(name)||'-',',') within group(order by area asc, detail asc) over(partition by area,detail),
listagg(to_char(tags)||'-'||to_char(typecode),',') within group(order by area asc, detail asc) over(partition by area,detail)
from acc_persons where area is not null order by area asc;

 

posted on 2024-05-28 16:33  丶柚子  阅读(1462)  评论(0)    收藏  举报

导航