当前位置: 代码网 > it编程>数据库>Oracle > oracle中行转列LISTAGG()函数详解及应用实例

oracle中行转列LISTAGG()函数详解及应用实例

2024年06月17日 Oracle 我要评论
1.listagg()函数作为普通函数使用时就是查询出来的结果列转为行selectlistagg ( name_chs, ',' ) within group ( order by rownum )

1.listagg()函数作为普通函数使用时就是查询出来的结果列转为行

select
	listagg ( name_chs, ',' ) within group ( order by rownum ) name 
from
	gspuser 
where
	rownum <= 10

2.listagg()作为分组函数使用

例如,把每个班组下面的人员拼接成一行

select
	b.momteamname,
	listagg ( g.name_chs, ',' ) within group ( order by b.momteamname ) res
from
	dgmomptdgmomglhqybzgl b 
	left join dgmomptaboutusers u on b.id = u.parentid 
	left join gspuser g on u.momemployeeid = g.id 
where
	b.momdatastate = 0 
	and u.momdatastate = 0 
group by
	b.momteamname

3.listagg()做分析函数使用

例如,查询每个班组下面有哪些人,统计每组人数量

select
    momteamname,res,count
from(	
 select
	b.momteamname,
	listagg ( g.name_chs, ',' ) within group ( order by b.momteamname ) over(partition by b.momteamname) res,
	count(g.name_chs) over(partition by b.momteamname) count,
	row_number() over(partition by b.momteamname order by rownum) rn
from
	dgmomptdgmomglhqybzgl b 
	left join dgmomptaboutusers u on b.id = u.parentid 
	left join gspuser g on u.momemployeeid = g.id 
where
	b.momdatastate = 0 
	and u.momdatastate = 0 
) where rn = 1

附:高级用法

listagg(xxx,’,’) within group (order by xxx) over (partition by xxx) rank

示例

with temp as(  
select 500 population, '中国' nation ,'江苏' city from dual union all  
select 1500 population, '中国' nation ,'上海' city from dual union all  
select 500 population, '中国' nation ,'北京' city from dual union all  
select 1000 population, '美国' nation ,'纽约' city from dual union all  
select 500 population, '美国' nation ,'波士顿' city from dual union all  
select 500 population, '日本' nation ,'东京' city from dual   
)  
select population,  
nation,  
city,  
listagg(city,',') within group (order by city) over (partition by nation) rank  
from temp复制

运行结果

总结 

到此这篇关于oracle中行转列listagg()函数详解及应用实例的文章就介绍到这了,更多相关oracle行转列listagg()内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com