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

どちらが間違っています。私は近くにいるようですが、次のステップは何なのかわからないのではないかと思います...

任意のヒント?

4

1 に答える 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, '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
/ 

両方のアプローチ (およびその他) をここに示します

于 2011-06-15T16:38:59.117 に答える