使用先前的connect连接字段

问题描述

| 具有表
my_tabe
M01 |   1
M01 |   2
M02 |   1
我想查询它以获得:
M01 |   1,2
M02 |   1
我设法通过使用以下查询关闭
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 scycle,sdate,rownum rn
    from my_tabe
    order by 1 desc
)
START WITH rn = 1
CONNECT BY PRIOR rn = rn - 1
屈服:
SCYCLE      |   RES
M02         |   1,2,1
M01         |   1,2
哪有错看来我已经接近了,但恐怕下一步是什么... 有小费吗?     

解决方法

        您需要将
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,listagg (sdate,\') 
within group (order by sdate) res
from my_tabe
group by scycle
/ 
此处显示了两种方法(和其他方法)。