Hi @J Like MIB ,
Or maybe you want this:
;with cte1 as (select p1.id1+p1.id2 as "ParentID", de1.balanceAmt as "ParentBalance",
p2.id1+p2.id2 as "ChildID" ,de2.balanceAmt as "ChildBalance"
from parentTbl p1
left join crossTbl cr
on p1.id1 = cr.pid1
and p1.id2 = cr.pid2
left join parentTbl p2
on cr.cid1 = p2.id1
and cr.cid2 = p2.id2
left join detailTbl de1
on p1.id1 = de1.id1
and p1.id2 = de1.id2
left join detailTbl de2
on p2.id1 = de2.id1
and p2.id2 = de2.id2
)
,cte2 as (
select *,dense_rank()over(order by ParentID) as part from cte1 where ChildID is not null and ChildBalance is not null
)
,cte3 as(
select * from cte2 cross apply ( values
( 'ParentID', 'ParentBalance'),
('ChildID','ChildBalance')
) c([ParentID/ChildID], [ParentBalance/ChildBalance])
)
,cte4 as(
select [ParentID/ChildID],[ParentBalance/ChildBalance],n,[1],[2],part from cte3 cross apply (values(ParentID,ParentBalance,1),
(ChildID,ChildBalance,2))d([1],[2],n)
)
,cte5 as(
select distinct [ParentID/ChildID],[ParentBalance/ChildBalance] ,[1],[2],part
from cte4 where ([ParentID/ChildID]='ParentID' and n=1) or ([ParentID/ChildID]='ChildID' and n=2 )
)select [ParentID/ChildID],[ParentBalance/ChildBalance],[1] AS [ParentID/ChildID2] ,[2] AS [ParentID/ChildID2]from cte5 order by part,[ParentID/ChildID] desc
Best regards,
Niko
----------
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.