2014-03-27 37 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