使用先前连接连接字段

时间:2011-06-15 15:55:31

标签: oracle string-aggregation

拥有下表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

哪个错了。这似乎我很接近,但我担心我不会做下一步...

任何提示?

1 个答案:

答案 0 :(得分: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, '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
/ 

两种方法(和其他方法)都显示为here