Skip to content Skip to sidebar Skip to footer

Sql Revising Table Data To A More Compact Form

I have a table with data pairs modeled like the following: Id1 Id2 ----------- 100 50 120 70 70 50 34 20 50 40 40 10 Id1 is always bigger then Id2. The pa

Solution 1:

declare @t table(Id1 int, Id2 int)
insert @t values (100, 50)
insert @t values (    120,    70)
insert @t values (    70,     50)
insert @t values (    34,     20)
insert @t values (    50,     40)
insert @t values (    40,     10)

;with a as
(
-- find all rows without parent <*>
select id2, id1 from @t t where not exists (select 1 from @t where t.id1 = id2)
union all -- recusive work down to lowest child while storing the parent id1 
select t.id2 , a.id1
from a
join @t t on a.id2 = t.id1
)
-- show the lowest child for each row found in <*>
select id1, min(id2) id2 from a
group by id1

Result:

id1         id2
----------- -----------
34          20
100         10
120         10

Post a Comment for "Sql Revising Table Data To A More Compact Form"