with t as ( select 'A' as product,1 as sno from dual union all select 'A',2 from dual union all select 'A',4 from dual union all select 'B',3 from dual union all select 'B',5 from dual union all select 'B',6 from dual ) select product, listagg(sno,',') within group(order by rn) sno from ( select product, decode(min(sno),max(sno),min(sno),min(sno)||'-'||max(sno)) sno, min(rn) rn from ( select product, to_char(sno) sno, row_number() over(partition by product order by sno) rn from t ) group by product, rn - sno ) group by product