0

我有一个存储用户替换的表(ms sql 2008)。它的形式是:

| ID| U1| U2|

| 1 | A | B |

| 2 | B | C |

| 3 | C | D |

用户 A 被用户 B 替换。然后 B 被 C 替换,然后 C 被 D 替换。替换可能是 1-n。

我怎样才能在一行中得到(逻辑)结果,现在 A 被 D 替换了?

| A | D |
4

1 回答 1

1

使用递归 CTE,您可以找到每一行的最终替换。

WITH RCTE AS
(
    SELECT ID, U1, U2, 1 AS Lvl 
    FROM dbo.table1 --WHERE ID = 1
    UNION ALL
    SELECT r.ID, r.U1, t1.U2, r.Lvl + 1 
    FROM dbo.table1 t1
    INNER JOIN RCTE r ON r.U2 = t1.U1 AND t1.ID > r.ID
)
, CTE_RN AS 
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Lvl DESC) RN 
    FROM RCTE
)
SELECT ID, u1, U2 AS FinalReplacement
FROM CTE_RN c
WHERE RN = 1 
AND NOT EXISTS (SELECT * FROM dbo.table1 t1 WHERE c.u1 = t1.U2)

SQLFiddle 演示

于 2013-10-23T08:17:21.920 回答