连接 Oracle 中多行的列值而不重复
concatenate column values from multiple rows in Oracle without duplicates
我可以 concatenate column values from multiple rows in Oracle 使用 LISTAGG
但我想避免重复
目前 return 重复
select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;
例如数据
ID
10
10
20
30
30
40
Returns 10,10,20,30,40,40
改为10,20,30,40
而且我无法在 LISTAGG
中使用 distinct
select LISTAGG( distinct t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;
错误
ORA-30482: DISTINCT option not allowed for this function
您可以将 distinct 放在子查询中:
select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from (SELECT DISTINCT t.id FROM TABLE) t
一个选项是使用 regexp_replace()
:
select regexp_replace(
listagg( t.id,',') within group (order by t.id)
, '([^,]+)(,)+', '') as "Result"
from t
我可以 concatenate column values from multiple rows in Oracle 使用 LISTAGG
但我想避免重复
目前 return 重复
select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;
例如数据
ID
10
10
20
30
30
40
Returns 10,10,20,30,40,40
改为10,20,30,40
而且我无法在 LISTAGG
distinct
select LISTAGG( distinct t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;
错误
ORA-30482: DISTINCT option not allowed for this function
您可以将 distinct 放在子查询中:
select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from (SELECT DISTINCT t.id FROM TABLE) t
一个选项是使用 regexp_replace()
:
select regexp_replace(
listagg( t.id,',') within group (order by t.id)
, '([^,]+)(,)+', '') as "Result"
from t