April 21, 2011 at 2:57 pm
Team,
I have a table with the following data showing parent-child relationship
AccountID Parent ID
-------------------
1 2
2 3
3
I need a query to list the hierarchy in the following format, indicating that 2 is the parnet of 1 and 3 is the parent of 2, in one row. Any ideas, please. Thanks a lot.
Result
----------
1 2 3
April 21, 2011 at 3:29 pm
Hi,
you can use a common table expression CTE like:
;with cte_Childs(
RelationString,
AccountID
)as(
select cast(r.AccountID as nvarchar),
r.AccountID
from RelationShipTable r
left join
RelationShipTable t on r.ParentID=t.AccountID
where t.AccountID is null
union all
select c.RelationString + ' ' + cast(r.AccountID as nvarchar),
r.AccountID
from cte_Childs c
inner join
RelationShipTable r on c.AccountID = r.ParentID
)
select max(RelationString)
from cte_Childs
[font="Arial"]Kind regards,
Patrick Fiedler
Consultant
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply