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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(随手记,oracle,数据库,sql)