Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Collect all the ID of subordinate groups

Author  Topic 

pascal_jimi
Posting Yak Master

167 Posts

Posted - 2014-12-05 : 07:15:08
Good day

There is a table with the id and categories Parentid.

The challenge is this: you need to collect in each category one drain all the ID that concern it.
For Example:

declare @t table (
[id] [bigint],
[Parentid] [bigint],
[Name] [nvarchar](50)
)

insert into @t


select 1 as [Id], Null [Parentid] , N'category1'[Name] union all
select 2 as [Id], 1 [Parentid] , N'category2'[Name] union all
select 3 as [Id], 2 [Parentid] , N'category3'[Name] union all
select 4 as [Id], 2 [Parentid] , N'category4'[Name] union all
select 5 as [Id], Null [Parentid] , N'category5'[Name] union all
select 6 as [Id], 5 [Parentid] , N'category6'[Name]
select * from @t;

The result should be:


1 NULL category1 2;3;4
2 1 category2 3;4
3 2 category3
4 2 category4
5 NULL category5 6
6 5 category6


Thanks in advance!

http://sql-az.tr.gg/

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2014-12-06 : 18:53:08
Try this:
with cte1 (id,parentid)
as (select id
,parentid
from @t
union all
select a.id
,b.parentid
from cte1 as a
inner join @t as b
on b.id=a.parentid
where b.parentid is not null
)
,cte2 (id,parentids)
as (select id
,stuff((select ','+cast(parentid as varchar(max))
from cte1 as b
where b.id=a.id
order by parentid
for xml path ('')
)
,1,1,''
) as parentids
from @t as a
where parentid is not null
)
,cte3 (id,nextids)
as (select distinct
parentid as id
,stuff((select ','+cast(id as varchar(max))
from cte1 as b
where b.parentid=a.parentid
order by id
for xml path ('')
)
,1,1,''
) as nextids
from @t as a
where parentid is not null
)
select a.id
,a.name
,b.parentids
,c.nextids
from @t as a
left outer join cte2 as b
on b.id=a.id
left outer join cte3 as c
on c.id=a.id
order by a.id
This will produce:
id name      parentids nextids
1 category1 NULL 2,3,4
2 category2 1 3,4
3 category3 1,2 NULL
4 category4 1,2 NULL
5 category5 NULL 6
6 category6 5 NULL
Go to Top of Page
   

- Advertisement -