2014-03-27 82 views
0

我需要連接存儲在oracle表中的逗號分隔列值。當我連接列值時,我還需要刪除重複的值。我是oracle新手,不確定從哪裏開始。有人可以幫助我在oracle 11g中實現以下功能嗎?連接逗號分隔的列值是刪除重複項

Table: 
rec_id  affiliations 
1   P,QE,D 
2   EE,ED-D 
1   QE,PO-D, D 
2   A,EE 

Desired output: 
rec_id affiliations 
1   P,QE,D,PO-D 
2   EE,ED-D,A,EE 

回答

2

該查詢的第一部分將輸入解析爲每個聯屬單獨的一行;最終的select將它們連接成每個rec_id的單個列表。

with parsed as (
    select distinct 
     rec_id 
     ,ltrim(regexp_substr(','||affiliations,',([^,])+',1,i), ',') k 
    from t, (select rownum i from dual connect by level <= 100) 
    where regexp_substr(','||affiliations,',([^,])+',1,i) is not null) 
select distinct 
     rec_id 
     ,listagg(k, ',') within group (order by k) over (partition by rec_id) affiliations 
from parsed 
order by rec_id; 

將數字(例如100)調整爲您希望在輸入中看到的項目的最大數量。

http://sqlfiddle.com/#!4/37b44/4