oracle中行转列LISTAGG()函数详解及应用实例
作者:sym@12
这篇文章主要给大家介绍了关于oracle中行转列LISTAGG()函数详解及应用实例的相关资料,stagg是oracle11.2增加的特性,功能类似wmsys.wm_concat函数,即将数据分组后,把指定列的数据通过指定符号合并,需要的朋友可以参考下
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()内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!