2013-12-14 77 views
1

在Oracle 11g 1.1版中構建SQL以連接來自多行的列值是否可能?在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組成的總和(數量)組的串聯。

SQL的任何幫助?我正在使用Oracle 11g 1.1版。所以listagg()函數不起作用。實際上我不想使用collect()函數。我的意思是不需要改變當前的表結構。

回答

1

你可以嘗試wm_concat(),不支持的功能:

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

Here是在其他許多方面一個很好的資源,以得到這個甲骨文完成。

編輯:

如果你不想寫自己的功能,你剛剛的事情少數彙集到一起,你可以使用條件聚合方法:

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"; 
+0

11.1正在使用。不支持wm_concat – Abhi

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;