Group Related Ids

create table #temp(id1 int,id2 int)
insert into #temp(id1,id2)
SELECT 11442244 ,11655008
union all select
11442246, 11655008
union all select
11442244 ,11709488
union all select
11442023, 11709488
union all select
11442247, 11709488
union all select
11442244, 11442246
union all select
11442023, 11655008
union all select
11442247 ,11655008
union all select
11442244, 11442247
union all select
11442246, 11442247

union all select

1,2

How do i group all the related items into a single group like below.

1, 2
11442023,11442244, 11442246, 11442247, 11655008, 11709488

August 24th, 2015 8:02pm

create table #temp(id1 int,id2 int)
insert into #temp(id1,id2)
SELECT 11442244 ,11655008
union all select
11442246, 11655008
union all select
11442244 ,11709488
union all select
11442023, 11709488
union all select
11442247, 11709488
union all select
11442244, 11442246
union all select
11442023, 11655008
union all select
11442247 ,11655008
union all select
11442244, 11442247
union all select
11442246, 11442247

union all select

1,2

s
;with mycte as (
select id1 from #temp
union select id2 from #temp)
SELECT 
       Stuff(( SELECT ',' + Cast(t2.id1 as varchar(10))
           FROM mycte t2
          WHERE len(t1.id1) =  len(t2.id1)
         
            FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1,'')  AS ids
  FROM mycte t1
 GROUP BY  len(t1.id1)

drop table #temp

Free Windows Admin Tool Kit Click here and download it now
August 24th, 2015 8:20pm

Hi

Trying to find the groups of related items, 

if 1 -> is related to 2

2-> 3

3-> 5 

5->9 then 1,2,3,5 should be in one group.

August 24th, 2015 8:45pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics