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
SELECT product
, LISTAGG(DECODE(x, sno, '-', '', '', ',') || sno) WITHIN GROUP(ORDER BY sno) x
FROM (SELECT product, sno
, LAG (sno) OVER(PARTITION BY product ORDER BY sno) + 1 x
, LEAD(sno) OVER(PARTITION BY product ORDER BY sno) - 1 y
FROM t
)
WHERE LNNVL(x = y)
GROUP BY product
;
LNNVL이 이렇게 사용될 줄이야0-0