I have a table like this:
id col1 col2
----------- ---- -----------
1 A 5
2 A 6
3 B 5
4 B
This is not an easy one to solve through straight SQL. I figured I'd give it a crack using a recursive CTE. This spits out all possible combinations, but... in one field called "path" here. Perhaps it will present a way forward using straight tsql.
With recCTE AS
(
SELECT
col1,
col2,
0 as depth,
CAST(col1 + '|' + CAST(col2 AS varchar(10)) AS VARCHAR(30)) as path
FROM t
UNION ALL
SELECT
t1.col1,
t1.col2,
rec.depth + 1,
CAST(rec.path + '>' + t1.col1 + '|' + cast(t1.col2 as varchar(10)) as varchar(30))
FROM t t1
INNER JOIN recCTE rec
ON rec.path NOT LIKE '%|' + CAST(t1.col2 as varchar(10)) + '%'
AND rec.path NOT LIKE '%' + CAST(t1.col2 as varchar(10)) + '|%'
WHERE depth + 1 <= 3
)
SELECT *
FROM recCTE
WHERE depth = 2