Привет, вот запрос того, чего вы пытаетесь достичь.
with your_data as (
select 'A,B,C,D' medicine_name, 'D1' disease from dual union
select 'A,C,B', 'D2' from dual union
select 'D,C,A,B', 'D3' from dual union
select 'D,A', 'D4' from dual
),
split as (select distinct regexp_substr(medicine_name,'[^,]+', 1, level) as medicine_name, disease from your_data
connect by regexp_substr(medicine_name,'[^,]+', 1, level) is not null),
aggr as (
select disease, listagg(medicine_name,',') within group (order by medicine_name) medicine_name from split
group by disease),
input as (select distinct regexp_substr('A,B,C','[^,]+', 1, level) as medicine_name from your_data
connect by regexp_substr('A,B,C','[^,]+', 1, level) is not null),
aggr_input as (
select listagg(medicine_name,',') within group (order by medicine_name) medicine_name from input)
select a.* from aggr a
join aggr_input ai on ai.medicine_name = substr(a.medicine_name,1,length(ai.medicine_name))
Просто замените на your_data as (select medicine_name, disease from med_disease)
и жестко закодируйте 'A, B, C' своим входным параметром.
Дайте мне знать, как это происходит: -)