2017-04-03 96 views
1

我的當前表格對於1個用戶來說是這樣的。TSQL中的數據透視記錄

NewCustomerID OldCustomerID RowID  Date 
111    NULL    1  2016-01-01 
222    111    321  2016-02-05 
333    222    5433  2017-03-01 
444    333    95312 2017-04-03 

下表是我最終結果所需要的。需要TSQL。

NewCustomerID OldCustomerID 
444    111    
444    222    
444    333 

我將使用上表更新所有OldCustomerID的最新NewCustomerID

+1

什麼是由''NewCustomerID'成爲444'每'OldCustomerID'相關的邏輯是什麼? –

+1

@TimBiegeleisen我猜這些都是'444'在 – LONG

+0

之前使用的所有歷史ID客戶正在從一個位置遷移到另一個位置,所以他的customerID不斷變化。每當customerID發生變化時,都會記錄它是什麼以及現在是什麼。 – Etienne

回答

2

你正在尋找一個遞歸CTE:

with cte as (
     select t.NewCustomerID, t.OldCustomerID 
     from t 
     where not exists (select 1 from t t2 where t2.OldCustomerId = t.NewCustomerID) 
     union all 
     select cte.NewCustomerId, t.OldCustomerID 
     from cte join 
      t 
      on t.NewCustomerID = cte.OldCustomerID 
    ) 
select * 
from cte; 

Here是它的工作的例子。

+0

嗨戈登,'union all'的第一部分'1'是什麼?似乎列數不匹配? – LONG

+0

以上對我不起作用,它不返回我的最終結果,因爲在我的問題:( – Etienne

+0

@Etienne ...。它現在應該工作 –

1

試試這個

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 
相關問題