Вам нужно ограничить ваше connect by
тем же значением scycle
, а также посчитать количество совпадений и отфильтровать их, чтобы избежать промежуточных результатов.
with my_tabe as
(
select 'M01' as scycle, '1' as sdate from dual union
select 'M01' as scycle, '2' as sdate from dual union
select 'M02' as scycle, '1' as sdate from dual
)
select scycle, ltrim(sys_connect_by_path(sdate, ','), ',')
from
(
select distinct sdate,
scycle,
count(1) over (partition by scycle) as cnt,
row_number() over (partition by scycle order by sdate) as rn
from my_tabe
)
where rn = cnt
start with rn = 1
connect by prior rn + 1 = rn
and prior scycle = scycle
/
SCYCLE LTRIM(SYS_CONNECT_BY_PATH(SDATE,','),',')
------ -----------------------------------------
M01 1,2
M02 1
Если вы используете 11g, вы можете использовать встроенную функцию LISTAGG
вместо:
with my_tabe as
(
select 'M01' as scycle, '1' as sdate from dual union
select 'M01' as scycle, '2' as sdate from dual union
select 'M02' as scycle, '1' as sdate from dual
)
select scycle, listagg (sdate, ',')
within group (order by sdate) res
from my_tabe
group by scycle
/
Оба подхода (и другие) показаны здесь .