如果你第一次一起加入你的表:
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 –