查找列链值-后续

时间:2018-07-09 07:53:33

标签: sql-server tsql sql-server-2008-r2 common-table-expression recursive-query

这是this的后续问题。

表格:

Merged Array: [ {a: 'HI!'}, {b: 'HOW'} {c: 'ARE'}, {d: 'YOU?'} ]

记录:

已编辑

create table tbl_test
(
    col1 int,
    col2 int
);

查询:我想以INSERT INTO tbl_test VALUES(111,112), (112,113), (113,114), (114,111), (115,116), (117,118), (118,119), (119,117), --Added (111,130), (120,121), (122,123), (123,111), (124,111); 的形式找到完整的链col1和col2 (这是完整的链,因为它以111->112->113->114->111开头并以111结尾)。

注意:表中可能有多个链。

预期的输出2:

111

尝试了gotqn的答案:

col1    col2
-------------
111     112
112     113
113     114
114     111 
117     118
118     119  
119     117

但无法获得第二条链。

1 个答案:

答案 0 :(得分:1)

尝试一下

WITH DataSource AS
(
    SELECT col1
          ,col2
          ,0 as level
          ,ROW_NUMBER() OVER(ORDER BY Col1, col2) AS [groupID]
          ,0 as anchorMatched
          ,col1 as startValue
    FROM tbl_test
    WHERE col1 IN (Select col2 from tbl_test where (col2-col1)<>1 )
    UNION ALL
    SELECT A.col1
          ,A.col2
          ,level + 1
          ,B.[groupID]
          ,anchorMatched + CASE WHEN A.col2 = B.startValue THEN 1 ELSE 0 END
          ,b.startValue
    FROM tbl_test A
    INNER JOIN DataSource B
        ON A.col1 = B.col2
    WHERE (anchorMatched = 0 AND A.col1 <> B.startValue AND (A.col2 = A.col1 +1 or A.col2 = B.startValue))
)
SELECT *
FROM DataSource where groupID in (SELECT groupID FROM DataSource where anchorMatched = 1)
order by col1,groupID