I have a SQL Server 2005 table as follows:
parent child
1 a
2 a
2 b
3 b
3 c
4 c
5 d
6 d
7 d
8 e
9 e
9 f
10 f
Each parent can have one or more child, each child can also have one or more parents.
How can I find (or group) all parents that are related?
In above case, I want to group:
parent 1, 2, 3, 4 into group 1
parent 5, 6, 7 into group 2
parent 8, 9, 10 into group 3
A result from the query would look like: (Doesn’t matter which parent use as group as long as it is from one of those parent in the group, min ID, or max ID would do)
parent child parent_group
1 a 1
2 a 1
2 b 1
3 b 1
3 c 1
4 c 1
5 d 5
6 d 5
7 d 5
8 e 8
9 e 8
9 f 8
10 f 8
This is similar to those standard boss – subordinate recursive SQL questions except the subordinate may have more than 1 boss.
Is it possible to use SQL to generate result as above? If so how?
Appreciate any help.
There is no way to do this in a single query. I found a blog post (with some ruby code) describing how you can calculate connected components in SQL (MySQL flavor).
Based on the article, I wrote the following SQL (SQL Server flavor):
You could wrap this up in a stored procedure:
And then call it with
Output: