Solved

CTE to list all children per node in hierarchy

Posted on 2011-02-14
11
994 Views
Last Modified: 2012-05-11
ParentChildTb
ID    Parent
004  003
003  002
002  001
001  001
Desired Output:
Parent Child
001  002
001  003
001  004
002  003
002  004
003  004
I need a query that traverses through a tree and gets all children, grandchildren, etc. per item
Each item can have many children on different levels and each child can have multiple parents.

Thank you!
0
Comment
Question by:larisa1970
  • 4
  • 3
  • 2
11 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
this should do:
with data as (
  select id, parent from ParentChildTb t where not exists ( select null from ParentChildTb x where x.id = t.Parent )
 UNION ALL
 select t.id, t.parent from ParentChildTb t join data on data.id = t.parentid
)
select * from data

Open in new window

0
 

Author Comment

by:larisa1970
Comment Utility
Angelll,
thanks, but you query doesn't return anything.
It should return more records than in the original table
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
sorry, I see:
with data as (
  select id, parent from ParentChildTb t where id = parent)
 UNION ALL
 select t.id, t.parent from ParentChildTb t join data on data.id = t.parentid
)
select * from data

Open in new window

0
 

Author Comment

by:larisa1970
Comment Utility

"The statement terminated. The maximum recursion 100 has been exhausted before statement completion."
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 40

Expert Comment

by:Sharath
Comment Utility
check this.
-- @ParentChildTb1 is your main table
declare @ParentChildTb1 table(ID int,Parent int)
insert @ParentChildTb1 values(4,3)
insert @ParentChildTb1 values(3,2)
insert @ParentChildTb1 values(2,1)
insert @ParentChildTb1 values(1,1)

-- Create a temp table, insert all the records from your main table and update the rool to NULL 
declare @ParentChildTb table(ID int,Parent int)
insert @ParentChildTb select * from @ParentChildTb1
update @ParentChildTb set Parent = NULL where ID = Parent

-- Try this CTE to get the Tree of parents
;WITH cte AS(
SELECT ID, Parent, coalesce(Convert(varchar(max),Parent)+',','') AS Tree
  FROM @ParentChildTb
 WHERE Parent is null
 UNION ALL
SELECT c.ID, c.Parent, p.Tree + ',' + CAST(c.Parent AS varchar(max))
  FROM @ParentChildTb c
  JOIN cte p
    ON c.Parent = p.ID
),cte2 as (
SELECT ID,Parent,SUBSTRING(Tree,2,LEN(Tree)) Tree FROM cte)
-- This query gives the desired output
select ParentID,ID ChildID from (
SELECT ID,ltrim(SUBSTRING(Tree, n, CHARINDEX(',', Tree + ',',n) - n)) AS ParentID
 FROM cte2
CROSS JOIN (SELECT number FROM master..spt_values WHERE type = 'P')  AS Numbers(n)
WHERE SUBSTRING(',' + Tree, n, 1) = ','
  AND n < LEN(Tree) + 1) t1
order by ParentID,ID
/*
ParentID	ChildID
1	2
1	3
1	4
2	3
2	4
3	4
*/

Open in new window

0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
of course...
with data as (
  select id, parent from ParentChildTb t where id = parent)
 UNION ALL
 select t.id, t.parent from ParentChildTb t join data on data.id = t.parentid and t.id <> t.parentid
)
select * from data

Open in new window

0
 
LVL 40

Accepted Solution

by:
Sharath earned 500 total points
Comment Utility
I am not sure why did you accept http:#34892392. First thing is there are syntactical errors in that query. Forget about syntax errors. The query is not producing the expected result.
declare @ParentChildTb1 table(ID int,Parent int)
insert @ParentChildTb1 values(4,3)
insert @ParentChildTb1 values(3,2)
insert @ParentChildTb1 values(2,1)
insert @ParentChildTb1 values(1,1)

;with data as (
  select id, parent from @ParentChildTb1 t where id = parent
 UNION ALL
 select t.id, t.parent from @ParentChildTb1 t join data on data.id = t.Parent and t.id <> t.Parent
)
select * from data
/*
id	parent
1	1
2	1
3	2
4	3
*/

Open in new window

0
 
LVL 40

Expert Comment

by:Sharath
Comment Utility
I would suggest Option #3: Accept one or more comments as the solution.The correct answer would be http:#a34890907
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
well, when I analyse the question in deep, even Sharath's code will not solve all the scenarios properly without an additional distinct.

>Each item can have many children on different levels and each child can have multiple parents.
this was not in the test case neither, and will result in duplicates.

I presumed the asker was happy with the simple code ...


so my suggestion would be to split between the original accepted comment and Sharath's comment
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

by Mark Wills PIVOT is a great facility and solves many an EAV (Entity - Attribute - Value) type transformation where we need the information held as data within a column to become columns in their own right. Now, in some cases that is relatively…
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now