Reputation: 1514
I am having a table name factors
. It contains data like this:
id Name paretnID
1 abc 0
2 xyz 0
3 abc1 1
4 abc2 1
5 abc3 1
6 qwe 0
7 xyz1 2
8 xyz2 2
I have a set of ids like this: (1,4,7,8)
I want to show all the parent and child ids. Like this
id name parentID
1 abc 0
2 xyz 0
4 abc2 1
7 xyz1 2
8 xyz2 2
In my id list 2
is not present but id 2
is the parent of 7
and 8
so it is showing in the result set.
How to write query to show above result?
Upvotes: 2
Views: 3846
Reputation: 222
Had the same problem, solved it with something like this...
SELECT b.*
FROM factors AS a
JOIN factors AS b
ON a.parentID = b.id
WHERE a.id IN (1,4,7,8)
Upvotes: 1
Reputation: 27367
Declare @a table (id int , Name Varchar(100) , parentID int)
Insert into @a
Select 1,'abc',0
UNION Select 2,'xyz',0
UNION Select 3,'abc1',1
UNION Select 4,'abc2',1
UNION Select 5,'abc3',1
UNION Select 6,'qwe',0
UNION Select 7,'xyz1',2
UNION Select 8,'xyz2',2
;WITH Rollups AS (
SELECT Id, ParentId,Name
FROM @a Child WHERE ID in (1,4,7,8)
UNION ALL
SELECT cl.Id, cl.ParentId, cl.Name
FROM @a cl
INNER JOIN Rollups Children ON Children.ParentID = cl.Id
)
SELECT DISTINCT *
FROM Rollups
Order by ID
Upvotes: 2
Reputation: 6426
something like
SELECT
id.name,parentid
FROM
factors
WHERE
id IN (1,4,7,8)
UNION
SELECT
p.id.p.name,p.parentid
FROM factors c
JOIN factors p
ON c.parentid = p.id
WHERE
c.id IN (1,4,7,8)
Upvotes: 1