3 回答

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
19c及以后:
select listagg(distinct the_column, ',') within group (order by the_column)from the_table
18c及更早:
select listagg(the_column, ',') within group (order by the_column)from ( select distinct the_column from the_table) t
如果您需要更多列,那么您可能正在尋找以下內(nèi)容:
select col1, listagg(col2, ',') within group (order by col2)from ( select col1, col2, row_number() over (partition by col1, col2 order by col1) as rn from foo order by col1,col2)where rn = 1group by col1;

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個(gè)贊
以下是解決問題的方法。
select
regexp_replace(
'2,2,2.1,3,3,3,3,4,4'
,'([^,]+)(,\1)*(,|$)', '\1\3')
from dual
回報(bào)
2,2.1,3,4
答案(見下面的注釋):
select col1,
regexp_replace(
listagg(
col2 , ',') within group (order by col2) -- sorted
,'([^,]+)(,\1)*(,|$)', '\1\3') )
from tableX
where rn = 1
group by col1;
注意:以上內(nèi)容適用于大多數(shù)情況 - 列表應(yīng)該排序,您可能需要根據(jù)您的數(shù)據(jù)修剪所有尾隨和前導(dǎo)空格。
如果你在> 20或大字符串大小的組中有很多項(xiàng),你可能會(huì)遇到oracle字符串大小限制'字符串連接的結(jié)果太長(zhǎng)'所以在每個(gè)組的成員上放一個(gè)最大數(shù)字。這只有在可以僅列出第一個(gè)成員的情況下才有效。如果你有很長(zhǎng)的變量字符串,這可能不起作用。你將不得不進(jìn)行實(shí)驗(yàn)。
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;
另一種解決方案(沒那么簡(jiǎn)單),希望能夠避免oracle的字符串大小限制-字符串大小限制為4000感謝這個(gè)職位在這里通過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;
一些測(cè)試用例 - 僅供參考
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
項(xiàng)目中包含的項(xiàng)目,例如。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 - 正則表達(dá)式感謝伊戈?duì)?!適用于所有情況。
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

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
你可以使用未記錄的wm_concat
功能。
select col1, wm_concat(distinct col2) col2_list from tab1group by col1;
此函數(shù)返回clob列,如果您希望可以使用dbms_lob.substr
將clob轉(zhuǎn)換為varchar2。
添加回答
舉報(bào)