TSQL中的Pivot记录

时间:2017-04-03 12:07:19

标签: sql-server tsql sql-server-2012

My Current表对于1位用户来说是这样的。

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

2 个答案:

答案 0 :(得分: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就是它的一个例子。

答案 1 :(得分: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