oracle列转行函数listagg和vm_concat

wm_concat 和listagg 函数都可以实现对(单个或组合)列的合并,也可以看成是对某一列的“SUM”,这俩个函数功能相同,listagg是在11.2的版本中才首次出现的,wm_concat在12c版本中被取消。

常见用法

select t.job,listagg(t.ename,’,’) within group(order by hiredate asc) from scott.emp t group by t.job;

select t.job,wm_concat(t.ename) from scott.emp t group by t.job;

–去重
with tb as(
select sys_guid() id,‘t1’ name, ‘CLERK’ job from dual
union select sys_guid() id,‘t1’ name, ‘SALESMAN’ job from dual
union select sys_guid() id,‘t1’ name, ‘MANAGER’ job from dual
union select sys_guid() id,‘t1’ name, ‘CLERK’ job from dual
union select sys_guid() id,‘t2’ name, ‘MANAGER’ job from dual
union select sys_guid() id,‘t2’ name, ‘MANAGER’ job from dual
)
select t.name, wm_concat(distinct t.job) jobs from tb t group by t.name;
对比

wm_cancat函数行转列后,不会按照原有查询结果排序。listagg函数行转列后,会按照原有查询结果顺序排列。如果考虑到需要行转列,并且保持分组后顺序不变可以使用listagg来完成。

wm_concat的使用(listagg上限varchar4000)
select dev_id,regexp_replace(regexp_replace(wm,’,’,’;’),’#’,’,’) coords from
(select dev_id ,wm_concat(t.x||’#’||t.y) over(partition by t.dev_id order by gps_time) wm ,
row_number() over(partition by dev_id order by gps_time desc) rm
from t_dev_loc t where t.dev_id in (‘37080000000034798’,‘37080000000034488’)
and gps_time between to_date(‘2018-11-05 00:00:00’,‘yyyy-mm-dd hh24:mi:ss’) and sysdate
)where rm=1;
行转列排序2( 突破listagg上限进行行转列排序)

with tb as(
select sys_guid() id,‘t1’ name, ‘CLERK’ job from dual
union select sys_guid() id,‘t1’ name, ‘SALESMAN’ job from dual
union select sys_guid() id,‘t1’ name, ‘MANAGER’ job from dual
union select sys_guid() id,‘t1’ name, ‘CLERK’ job from dual
union select sys_guid() id,‘t2’ name, ‘MANAGER’ job from dual
union select sys_guid() id,‘t2’ name, ‘MANAGER’ job from dual
)
– 突破listagg上限进行行转列排序
select t.name,
xmlagg(xmlparse(content t.job || ‘,’ wellformed) order by t.id asc)
.getclobval() jobs
from tb t
group by t.name

作者:clannad_
链接:https://www.jianshu.com/p/92cfd2f150f9
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值