暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

数据治理上的行转列需求——用Oracle实现

追梦IT人 2025-06-30
483

在数据统计中,行转列是一种常见的需求。具体来说,就是将表中特定列的数据行进行去重处理,并将其转化为数据列。行转列分为两种,一种是把行的一个字段转为固定列,另外一种是行中的一个字段转为一列中的数据。

前几天在数据治理中,收到了一个不合理的需求,当然不合理归不合理,还是尽量满足这种不合理需求吧。

第一种方法:WM_CONCAT,这是Oracle早期版本时常用的第三方函数
with tt as 
(
  select 'dept1' dept,'person1'  person from dual union all
  select 'dept1' dept,'person2'  person from dual union all
  select 'dept1' dept,'person3'  person from dual union all
  select 'dept2' dept,'person4'  person from dual union all
  select 'dept2' dept,'person5'  person from dual 
)
select dept,WM_CONCAT(person) AS persons
  from tt
 group by dept;

第二种方法:Listagg,这是Oracle 11.2后出现的标准函数
with tt as 
(
  select 'dept1' dept,'person1'  person from dual union all
  select 'dept1' dept,'person2'  person from dual union all
  select 'dept1' dept,'person3'  person from dual union all
  select 'dept2' dept,'person4'  person from dual union all
  select 'dept2' dept,'person5'  person from dual 
)
select dept,Listagg(person,',') within group (order by person)     as ss 
  from tt 
 group by dept;

官方支持

  WM_CONCAT:非官方函数,Oracle 不提供官方支持

  LISTAGG:官方函数,Oracle 提供完整支持和文档

ORDER BY 支持

  WM_CONCAT:不支持 ORDER BY,结果顺序不确定

  LISTAGG:支持 ORDER BY,可精确控制结果顺序

分隔符控制

  WM_CONCAT:固定使用逗号作为分隔符,无法自定义

  LISTAGG:可自定义分隔符(如逗号、分号、空格等)

NULL 值处理

  WM_CONCAT:自动忽略 NULL 值

  LISTAGG:默认忽略 NULL 值,但可通过其他方式处理

性能

  WM_CONCAT:在大数据集上性能较差

  LISTAGG:优化更好,在大数据集上性能更佳

版本兼容性

  WM_CONCAT:在较旧版本(如 10g、11g)中可用

  LISTAGG:从 11gR2 开始引入,较新版本均支持

结果类型

  WM_CONCAT:返回 CLOB 类型

  LISTAGG:返回 VARCHAR2 类型(可通过 CAST 转换为 CLOB)

长度限制

  WM_CONCAT:结果长度受限于 CLOB 类型

  LISTAGG:结果长度受限于 VARCHAR2 类型(默认 4000 字节),但可通过 CAST 转换突破限制


最后欢迎关注公众号:python与大数据分析



文章转载自追梦IT人,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论