By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
with t as (
select *
from (values (1, 2), (2, 7), (5, 7), (7, 10), (10, 11), (12, 13), (13, 14)) v(x, y)
),
tt as (
select v.x, v.y
from t cross apply
(values (x, y), (y, x)) v(x, y)
),
cte as (
select (case when tt.x < tt.y then tt.x else tt.y end) as lowest, v.val, tt.x, tt.y, convert(varchar(max), concat(',', tt.x, ',', tt.y, ',')) as vals
from tt cross apply
(values (x), (y)) v(val)
union all
select (case when tt.y < cte.lowest then tt.y else cte.lowest end) as lowest, cte.val, cte.x, tt.y, concat(cte.vals, tt.y, ',') as vals
from cte join
tt
on cte.y = tt.x and cte.vals not like concat('%,', tt.y, ',%')
union all
select (case when tt.x < cte.lowest then tt.x else cte.lowest end) as lowest, cte.val, tt.x, cte.y, concat(cte.vals, tt.x, ',') as vals
from cte join
tt
on cte.x = tt.y and cte.vals not like concat('%,', tt.x, ',%')
)
select min(lowest), val
from cte
group by val
(No column name) | val |
---|---|
1 | 1 |
1 | 2 |
1 | 5 |
1 | 7 |
1 | 10 |
1 | 11 |
12 | 12 |
12 | 13 |
12 | 14 |