Form continous chain from a table SQL?

83 views Asked by At

Consider the following SQL table (#forming):

SeqNo StartStep EndStep
788 A B
788 A C
795 B C
797 C D
798 D F
798 D G
Chain 1 : A  TO  B  TO  C  TO  D  TO  F 
Chain 2 : A  TO  B  TO  C  TO  D  TO  G 
Chain 3 : A  TO  C  TO  D  TO  F 
Chain 4 : A  TO  C  TO  D  TO  G 

Expected output: So it would return all the above rows i.e. a total of 14 rows because of all the combinations:

SeqNo StartStep EndStep
788 A B
795 B C
797 C D
798 D F
788 A B
795 B C
797 C D
798 D G
788 A C
797 C D
798 D F
788 A C
797 C D
798 D G

Another example,

SeqNo StartStep EndStep
823 A B
826 B C
826 B D
826 B E
827 D F
827 D E
836 E C
837 C G

Chain 1 : A TO B TO C TO G

Chain 2 : A TO B TO D TO F

Chain 3 : A TO B TO D TO E TO C TO G

Chain 4 : A TO B TO E TO C TO G

EXPECTED OUTPUT

SeqNo StartStep EndStep
823 A B
826 B C
837 C G
823 A B
826 B D
827 D F
823 A B
826 B D
827 D E
836 E C
837 C G
823 A B
826 B E
836 E C
837 C G
1

There are 1 answers

6
Akina On
WITH 
cte1 AS (
    SELECT *, 
           DENSE_RANK() OVER (ORDER BY SeqNo) dr,
           ROW_NUMBER() OVER (ORDER BY SeqNo) rn
    FROM test
    ),
cte2 AS (
    SELECT SeqNo, StartStep, EndStep, CAST(',' + StartStep + ',' + EndStep + ',' AS NVARCHAR) path, rn, 1 sn
    FROM cte1
    WHERE dr = 1
    UNION ALL
    SELECT cte1.SeqNo, cte1.StartStep, cte1.EndStep, CAST(cte2.path + cte1.EndStep + ',' AS NVARCHAR), cte2.rn, cte2.sn + 1
    FROM cte2
    JOIN cte1 ON cte2.EndStep = cte1.StartStep
    ),
cte3 AS (
    SELECT rn, MAX(sn) sn
    FROM cte2
    GROUP BY rn
    )
SELECT test.SeqNo, test.StartStep, test.EndStep
FROM cte2
JOIN cte3 ON cte2.rn = cte3.rn
         AND cte2.sn = cte3.sn
JOIN test ON CHARINDEX(',' + test.StartStep + ',' + test.EndStep + ',', cte2.path) > 0
ORDER BY cte2.path, test.SeqNo
;

https://sqlize.online/sql/mssql2017/ec39e9511c9ee3751981a6f2bc94381c/