如果你第一次一起加入你的表:
select mt.id, mt.cust_mobile, mt.type, lt.parent_id
from master_table mt
left join link_table lt on lt.id = mt.id;
ID CUST_MOBIL TYPE PARENT_ID
---------- ---------- ----- ----------
1 9000230003 cust 2
2 8906784566 ret 8
3 7474747474 dist 7
4 4595274646 sdist 5
6 8588775958 cust 3
5 8588585958 fse
8 8588777758 dist
你然後可以使用分層查詢作爲內聯視圖或CTE,從任何開始3210個條目:
with cte (id, cust_mobile, type, parent_id) as (
select mt.id, mt.cust_mobile, mt.type, lt.parent_id
from master_table mt
left join link_table lt on lt.id = mt.id
)
select listagg(id ||','|| cust_mobile ||','|| type, ',')
within group (order by level) as result
from cte
start with type = 'cust'
connect by id = prior parent_id
group by connect_by_root(id);
RESULT
--------------------------------------------------------------------------------
1,9000230003,cust,2,8906784566,ret,8,8588777758,dist
6,8588775958,cust,3,7474747474,dist
這將每行的相關數據連接成用逗號分隔的單個值;然後使用listagg()
將這些組合條目中的每一個放入單個結果中。
只是爲了好玩,你也可以使用遞歸CTE(來自11gR2);在這裏,我已經搬到了CTE內部的初始級聯只是將其從listagg()
分開:
with rcte (id, id_mobile_type, root_id, hop) as (
select mt.id, mt.id ||','|| mt.cust_mobile ||','|| mt.type, mt.id, 1
from master_table mt
where mt.type = 'cust' -- starting condition
union all
select mt.id, mt.id ||','|| mt.cust_mobile ||','|| mt.type,
rcte.root_id, rcte.hop + 1
from rcte
join link_table lt on lt.id = rcte.id
join master_table mt on mt.id = lt.parent_id
)
select listagg(id_mobile_type, ',') within group (order by hop) as result
from rcte
group by root_id;
RESULT
--------------------------------------------------------------------------------
1,9000230003,cust,2,8906784566,ret,8,8588777758,dist
6,8588775958,cust,3,7474747474,dist
我已經使用多個循環和自我聯接做到了,我需要做它用 –
您需要連接的或水平更好地解釋預期產出。爲什麼結果有你提供的數據? –
1,9000230003,cust,8,8588777758,ret6 8588775958 cust,2,8906784566,ret,4,4595274646,sdist,5,8588585958,fse –