2011-06-15 59 views
1

具有如下表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 

這是錯誤的。這似乎我很接近,但我恐怕我不會有什麼下一步...

任何提示?

回答

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

+0

O11g不錯!謝謝! – filippo 2011-06-15 17:02:13