By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
9 rows affected
| Product | PP1 | PP2 | PP3 | PP4 | PP5 | PP6 |
|---|---|---|---|---|---|---|
| P1 | A | B | C | D | E | F |
| P2 | P | Q | R | S | T | null |
[1] AS [PP1],[2] AS [PP2],[3] AS [PP3],[4] AS [PP4],[5] AS [PP5],[6] AS [PP6]
[1],[2],[3],[4],[5],[6]
with rcte as
(
select Product, t.StartPoint, t.EndPoint, path = 1
from tbl t
where not exists
(
select *
from tbl x
where x.Product = t.Product
and x.EndPoint = t.StartPoint
)
union all
select t.Product, t.StartPoint, t.EndPoint, path = path + 1
from rcte r
inner join tbl t on t.Product = r.Product
and t.StartPoint = r.EndPoint
)
select Product, [1] AS [PP1],[2] AS [PP2],[3] AS [PP3],[4] AS [PP4],[5] AS [PP5],[6] AS [PP6]
from
(
select Product, Point = StartPoint, path
from rcte
union all
select Product, Point = EndPoint, path + 1
from rcte r
where not exists
(
select *
from tbl x
where x.Product = r.Product
and x.StartPoint = r.EndPoint
)
) d
pivot
(
max(Point)
for [path] in ([1],[2],[3],[4],[5],[6])
) p