oracle中行转列函数

一、问题描述

  有时在“相关子查询中”需要查询某个实体类对应的某个字段有多个值,如果不做行专列查询,会提示返回多个列的错误。例如:

  如上图所示,一个组合包,可能对应多个产品,需要你将所对应的多个产品都放到前台显示。

二、解决方法

  表结构设计如图:

  首先,我们这里采用相关子查询的方式来获取结果:

  组合包和产品是一对多的关系,故一个组合包可以对应多个产品:

select 
(select listagg(pp.product_name,',') within group(order by  pp.product_name)
from edu_group_product gpp,--组合包和产品关联表
edu_product pp--产品表
where gpp.group_id = gp.group_id
and gpp.product_id = pp.product_id
) products
from edu_group gp--组合包表
where gp.group_id = 1000;

  查询时间:

该函数结构:

LISTAGG(字段名,分隔符) WITHIN GROUP( ORDER BY 字段名)

三、说明

  1.想使用该函数,在本机的oracle上试了一会,发现总提示我“未找到要求的关键字”,反复核对关键字和字段名称,都无法解决。于是在服务器一个曾使用过该方法的表结构中尝试试用该方法,一次成功,瞬间明白可能是因为服务器版本不同的原因。一查果然啊:

select wm_concat(name) name from user;--10g写法
select listagg(name,',') within group (order by name) name from user;--11g写法

  2.使用wm_concat后果

select 
(select wm_concat(pp.product_name)from edu_group_product gpp,--组合包和产品关联表
edu_product pp--产品表
where gpp.group_id = gp.group_id
and gpp.product_id = pp.product_id
) products
from edu_group gp--组合包表
where gp.group_id = 1000;

  同样的表结构,同样的查询要求,使用wm_concate()函数结果:

                

  试了几次,最快是3秒多,大并发量下,要死人的。

  同样,在10g的数据库中试用该方法耗时也很长。

   

原文地址:https://www.cnblogs.com/brolanda/p/4685414.html