我有一个表(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 |
答案 0 :(得分:1)
使用recursive 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 DEMO 强>