I have a table that contains small groups of related nodes. I would like to be able to identify all the nodes that are related.
-- Example of some small related nodes.
-- (14) (5) (8) (10) (3)
-- / \ \ \ /
-- (11)-(2) (12)-(9) (7)
-- \ / / \
-- (4) (6) (1) (13)
DECLARE @Graph TABLE (
A SmallInt NOT NULL,
B SmallInt NOT NULL
)
INSERT INTO @Graph (A, B)
VALUES
(11, 2), ( 2, 14), ( 2, 4), ( 5, 12),
( 6, 12), ( 12, 9), ( 8, 9), (10, 7),
( 1, 7), ( 7, 13), ( 7, 3);
Desired Result
- 1, 13
- 2, 14
- 3, 13
- 4, 14
- 5, 12
- 6, 12
- 7, 13
- 8, 12
- 9, 12
- 10, 13
- 11, 14
- 12, 12
- 13, 13
- 14, 14
CTE That gets close to the correct answer, but not quite.
WITH Src AS (
SELECT A, B FROM @Graph
)
, Recurse (A, B) AS (
SELECT A, B FROM Src
UNION ALL
SELECT S.A, R.B FROM Src S INNER JOIN Recurse R ON S.B = R.A
)
, List AS (
SELECT A, B FROM Recurse
UNION SELECT A, A FROM Src
UNION SELECT B, B FROM Src
)
SELECT A, MAX(B) B FROM List GROUP BY A ORDER BY 1, 2;
Query Result
- 1, 13
- 2, 14
- 3, 3 <- Wrong result
- 4, 4 <- Wrong result
- 5, 12
- 6, 12
- 7, 13
- 8, 9 <- Wrong result
- 9, 9 <- Wrong result
- 10, 13
- 11, 14
- 12, 12
- 13, 13
- 14, 14
I decided to use the MAX node number to relate the nodes together, but some other method would be acceptable.