問題を解決する方法は次のとおりです。
select
regexp_replace(
'2,2,2.1,3,3,3,3,4,4'
,'([^,]+)(,\1)*(,|$)', '\1\3')
from dual
戻り値
2,2.1,3,4
オラクル19Cからそれはここに組み込まれて組み込まれています
18C以前からグループ内で試してみるここを参照
それ以外の場合は正規表現を使用
以下の回答:
select col1,
regexp_replace(
listagg(
col2 , ',') within group (order by col2) -- sorted
,'([^,]+)(,\1)*(,|$)', '\1\3') )
from tableX
where rn = 1
group by col1;
注:上記はほとんどの場合に機能します。リストはソートする必要があります。データによっては、すべての後続スペースと先行スペースをトリムする必要がある場合があります。
20を超えるグループまたは大きな文字列サイズのアイテムがたくさんある場合、Oracleの文字列サイズ制限「文字列連結の結果が長すぎる」に遭遇する可能性があります。
Oracle 12cR2から、このエラーを抑制することができます。ここを参照してください。または、各グループのメンバーに最大数を設定します。これは、最初のメンバーのみをリストしてもよい場合にのみ機能します。非常に長い変数文字列がある場合、これは機能しない可能性があります。実験する必要があります。
select col1,
case
when count(col2) < 100 then
regexp_replace(
listagg(col2, ',') within group (order by col2)
,'([^,]+)(,\1)*(,|$)', '\1\3')
else
'Too many entries to list...'
end
from sometable
where rn = 1
group by col1;
うまくいけばオラクルの文字列サイズ制限を回避する別の解決策(それほど単純ではない)-文字列サイズは4000に制限されています。この投稿のおかげで、user3465996
select col1 ,
dbms_xmlgen.convert( -- HTML decode
dbms_lob.substr( -- limit size to 4000 chars
ltrim( -- remove leading commas
REGEXP_REPLACE(REPLACE(
REPLACE(
XMLAGG(
XMLELEMENT("A",col2 )
ORDER BY col2).getClobVal(),
'<A>',','),
'</A>',''),'([^,]+)(,\1)*(,|$)', '\1\3'),
','), -- remove leading XML commas ltrim
4000,1) -- limit to 4000 string size
, 1) -- HTML.decode
as col2
from sometable
where rn = 1
group by col1;
V1-一部のテストケース-FYI
regexp_replace('2,2,2.1,3,3,4,4','([^,]+)(,\1)+', '\1')
-> 2.1,3,4 Fail
regexp_replace('2 ,2 ,2.1,3 ,3 ,4 ,4 ','([^,]+)(,\1)+', '\1')
-> 2 ,2.1,3,4 Success - fixed length items
V2-アイテム内に含まれるアイテム。2,21
regexp_replace('2.1,1','([^,]+)(,\1)+', '\1')
-> 2.1 Fail
regexp_replace('2 ,2 ,2.1,1 ,3 ,4 ,4 ','(^|,)(.+)(,\2)+', '\1\2')
-> 2 ,2.1,1 ,3 ,4 -- success - NEW regex
regexp_replace('a,b,b,b,b,c','(^|,)(.+)(,\2)+', '\1\2')
-> a,b,b,c fail!
v3-正規表現はIgorに感謝します!すべてのケースで機能します。
select
regexp_replace('2,2,2.1,3,3,4,4','([^,]+)(,\1)*(,|$)', '\1\3') ,
---> 2,2.1,3,4 works
regexp_replace('2.1,1','([^,]+)(,\1)*(,|$)', '\1\3'),
--> 2.1,1 works
regexp_replace('a,b,b,b,b,c','([^,]+)(,\1)*(,|$)', '\1\3')
---> a,b,c works
from dual