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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Custom Grouping Related Records

Author  Topic 

rka
Starting Member

6 Posts

Posted - 2011-07-08 : 06:41:06
I have a table data as:
Rec1 Rec2
----- -----
1 2
2 3
4 3
5 6


I want to group all the relating records with the minimum value of the related records
i.e.
1 relates to 2 thus minimum is 1
2 relates to 3 BUT 2 also matches 1 so minimum becomes 1
4 relates to 3 BUT 3 relates to 2 and 2 relates to 1 so minimum becomes 1
5 relates to 6 so minimum becomes 5

I am expecting the result to be:

Rec1 Rec2 Grouping
----- ----- -------
1 2 1
2 3 1
4 3 1
5 6 5

Can anyone help me with a T-SQL statement which can achieve this result?

Seventhnight
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2011-07-08 : 10:12:37
It would be clearer if Rec1 < Rec2 was always true...

Then cte1 & cte3 wouldn't really be necessary...


Declare @t table (
Rec1 int,
Rec2 int
)

Insert Into @t Select 1, 2
Insert Into @t Select 2, 3
Insert Into @t Select 4, 3
Insert Into @t Select 5, 6



Select * From @t


--Select * From @t

;with cte1 As (
Select *
From
(
Select * From @t
Union All
Select Rec1 = Rec2, Rec2 = Rec1 From @t
) A
Where Rec1 < Rec2
), cte2 As (
Select *, Grp = Rec1 From cte1
Union All
Select B.Rec1, B.Rec2, Grp = A.Rec1 From cte1 A Inner Join cte2 B On A.Rec2 = B.Grp
), cte3 As (
Select Rec1, Rec2, Grp = MIN(Grp)
From cte2
Group By Rec1, Rec2
)

Select A.*, B.Grp
From @t A
Inner Join cte3 B
On (A.Rec1 = B.Rec1 and A.Rec2 = B.Rec2)
or (A.Rec1 = B.Rec2 and A.Rec2 = B.Rec1)


Corey

I Has Returned!!
Go to Top of Page

rka
Starting Member

6 Posts

Posted - 2011-07-09 : 03:53:23
Thanks. Your solution does the trick. Much appreciated
Go to Top of Page
   

- Advertisement -