2016-02-10 26 views
2

我需要您對regexp_replace函數的幫助。我有一個包含重複項的串聯字符串值列的表。我如何消除它們?在Oracle中刪除逗號分隔字符串中的重複值

實施例:

Ian,Beatty,Larry,Neesha,Beatty,Neesha,Ian,Neesha 

我需要的輸出是

Ian,Beatty,Larry,Neesha 

的重複是隨機的,而不是在任何特定的順序。

Update--

這裏是我的表看起來如何

ID Name1 Name2 Name3  
1  a  b   c 
1  c  d   a 
2  d  e   a 
2  c  d   b 

有一排不同的名稱1,名稱,NAME3爲逗號分隔字符串,我需要每個ID一行。

ID Name 
1  a,c,b,d,c 
2  d,c,e,a,b 

我嘗試使用listagg與不同,但我不能刪除重複項。

+1

使用合適的聯結表 - 甚至是嵌套表 - 而不是逗號分隔列表的好原因是什麼。祝你好運。 –

+0

這看起來是[這個]的愚蠢(http://stackoverflow.com/questions/26672269/how-to-remove-duplicates-from-comma-separated-list-by-regex-in-oracle-regexp-代表 – Dave

+0

該模式是不同的,不適用於我的數據。僧侶仍然存在。 – Cindy

回答

0

因此,嘗試了這一點...

([^,]+),(?=.*[A-Za-z],[] ]*\1) 
+0

這沒有奏效@Dave。重複仍然存在 – Cindy

0

我不認爲你可以用regexp_replace做,如果重複的值不相鄰。一種方法是將值分開,消除重複項,然後將它們重新組合。

標記分隔字符串的常用方法是regexp_substrconnect by子句。使用綁定變量與您的字符串使代碼更清楚一點:

var value varchar2(100); 
exec :value := 'Ian,Beatty,Larry,Neesha,Beatty,Neesha,Ian,Neesha'; 

select regexp_substr(:value, '[^,]+', 1, level) as value 
from dual 
connect by regexp_substr(:value, '[^,]+', 1, level) is not null; 

VALUE       
------------------------------ 
Ian       
Beatty       
Larry       
Neesha       
Beatty       
Neesha       
Ian       
Neesha       

您可以使用它作爲一個子查詢(或CTE),從中獲得不同的值,然後重新組裝與listagg

select listagg(value, ',') within group (order by value) as value 
from (
    select distinct value from (
    select regexp_substr(:value, '[^,]+', 1, level) as value 
    from dual 
    connect by regexp_substr(:value, '[^,]+', 1, level) is not null 
) 
); 

VALUE       
------------------------------ 
Beatty,Ian,Larry,Neesha  

這是一個有點如果你正在尋找在表中的多個行作爲混淆連接,通過語法,但你可以使用非determinisitic參考,以避免循環更加複雜:

with t42 (id, value) as (
    select 1, 'Ian,Beatty,Larry,Neesha,Beatty,Neesha,Ian,Neesha' from dual 
    union all select 2, 'Mary,Joe,Mary,Frank,Joe' from dual 
) 
select id, listagg(value, ',') within group (order by value) as value 
from (
    select distinct id, value from (
    select id, regexp_substr(value, '[^,]+', 1, level) as value 
    from t42 
    connect by regexp_substr(value, '[^,]+', 1, level) is not null 
    and id = prior id 
    and prior dbms_random.value is not null 
) 
) 
group by id; 

     ID VALUE       
---------- ------------------------------ 
     1 Beatty,Ian,Larry,Neesha  
     2 Frank,Joe,Mary     

當然,如果您正確存儲關係數據,則這不是必需的;在列中使用分隔字符串不是一個好主意。

+0

我會試試這個,並讓你知道......數據實際上不存在作爲分隔字符串。它來自每個ID多行,我已經使用listagg將它們連接成每行ID爲1行 – Cindy

+0

@Cindy - 那麼爲什麼不在調用listagg之前獲得不同的值? –

相關問題