Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oracle 使用connect by PREVIOR连接字段_Oracle_String Aggregation - Fatal编程技术网

Oracle 使用connect by PREVIOR连接字段

Oracle 使用connect by PREVIOR连接字段,oracle,string-aggregation,Oracle,String Aggregation,具有下表“我的表”: 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,

具有下表“我的表”:

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,则可以使用内置功能:

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
/ 
这两种方法(和其他方法)都显示出来