SQL Query用于连接Oracle 11g 1.1版中多行的列值

时间:2013-12-14 12:15:16

标签: sql oracle oracle11g string-concatenation

是否可以在Oracle 11g 1.1版中构建SQL以连接多行的列值?

以下是一个例子:

Table A

dName cName amount  type
  A     B     100   water
  A     B     200   house
  A     C     400   air
  A     B     300   water

SQL的输出应该是 -

dName   CName  totalAmount  count      type
A        B       600         3     water,house
A        C       400         1         air       

删除重复类型也不同,如..

因此,输出结果的类型列基本上是表A中的类型值与dName和cName的sum(amount)组的串联。

SQL的任何帮助?我使用的是Oracle 11g 1.1版。所以listagg()函数不起作用。实际上我不想使用collect()函数。我的意思是不需要改变当前的表结构。

2 个答案:

答案 0 :(得分:1)

您可以尝试wm_concat(),这是一项不受支持的功能:

select dName, CName, totalAmount, "count", wm_concat("type") as "type"
from a
group by dName, CName, totalAmount, "count";

Here是在Oracle中完成此任务的许多其他方法的良好资源。

编辑:

如果您不想编写自己的函数并且只需要处理一些事情,则可以使用条件聚合方法:

select dName, CName, totalAmount, "count",
       (max(case when seqnum = 1 then "type" end) ||
        max(case when seqnum = 2 then ','||"type" end) ||
        max(case when seqnum = 3 then ','||"type" end) ||
        max(case when seqnum = 4 then ','||"type" end) ||
        max(case when seqnum = 5 then ','||"type" end)
       ) as "type"
from (select a.*,
             row_number() over (partition by dName, CName, totalAmount, "count"
                                order by "type"
                               ) as seqnum
     ) a
group by dName, CName, totalAmount, "count";

答案 1 :(得分:0)

在oracle 11g中尝试此查询:

select t1.dName,t1.CName,t2.TotalAmount,t2.count,t1.type from
(select dName,CName,LISTAGG(TYPE,',') within group(order by TYPE)as type
from
(select UNIQUE dName,CName,type from A)
group by dName, CName)t1,
(select dName,CName,sum(amount) as TotalAmount,count(amount) as count
from A group by dName, CName)t2
where t1.dName||t1.CName = t2.dName||t2.CName order by CName;

如果你不能使用listagg试试这个查询:

select t1.dName,t1.CName,t2.TotalAmount,t2.count,t1.type from
(select dName,CName,rtrim (xmlagg (xmlelement(e,TYPE||',')).extract ('//text()'), ',')  as type
from
(select UNIQUE dName,CName,type from A)
group by dName, CName)t1,
(select dName,CName,sum(amount) as TotalAmount,count(amount) as count
from A group by dName, CName)t2
where t1.dName||t1.CName = t2.dName||t2.CName order by CName;