IT俱乐部 Oracle oracle中行转列LISTAGG()函数详解及应用实例

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

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

SELECT
	LISTAGG ( NAME_CHS, ',' ) within GROUP ( ORDER BY ROWNUM ) name 
FROM
	GSPUSER 
WHERE
	ROWNUM 

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()内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/database/oracle/11968.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部