試試這個
DECLARE @SampleDAta AS TABLE
(
NewCustomerID int,
OldCustomerID int
)
INSERT INTO @SampleDAta VALUES (111, NULL),(222,111),(333,222),(444,333),(1111, NULL),(2222,1111),(3333,2222),(4444,3333),(5555,4444)
;with reTbl as (
select t.NewCustomerID, t.OldCustomerID, 1 as lev, t.NewCustomerID AS RootId
from @SampleDAta t
where t.OldCustomerID IS NULL
union all
select t.NewCustomerId, t.OldCustomerID, reTbl.lev +1, reTbl.RootId
from reTbl join
@SampleDAta t
on t.OldCustomerID = reTbl.NewCustomerID
),
LastestId AS
(
SELECT c.RootId, max(c.lev) AS MaxLevel
FROM reTbl c
GROUP BY c.RootId
)
select reTbl.NewCustomerID, reTbl1.NewCustomerID AS OldCustomerID
from reTbl
INNER JOIN reTbl reTbl1 ON reTbl.RootId = reTbl1.RootId
INNER JOIN LastestId t ON reTbl.RootId = t.RootId AND reTbl.lev = t.MaxLevel
WHERE reTbl.NewCustomerID != reTbl1.NewCustomerID
ORDER BY reTbl.NewCustomerID
什麼是由''NewCustomerID'成爲444'每'OldCustomerID'相關的邏輯是什麼? –
@TimBiegeleisen我猜這些都是'444'在 – LONG
之前使用的所有歷史ID客戶正在從一個位置遷移到另一個位置,所以他的customerID不斷變化。每當customerID發生變化時,都會記錄它是什麼以及現在是什麼。 – Etienne