Sql server TSQL中的Pivot记录
对于1个用户,我的当前表如下所示Sql server TSQL中的Pivot记录,sql-server,tsql,sql-server-2012,Sql Server,Tsql,Sql Server 2012,对于1个用户,我的当前表如下所示 NewCustomerID OldCustomerID RowID Date 111 NULL 1 2016-01-01 222 111 321 2016-02-05 333 222 5433 2017-03-01 444 3
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
我将使用上表将所有旧CustomerID更新为最新的新CustomerID您正在寻找递归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;
这是一个有效的例子。试试这个
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
历史ID,因此他的customerID不断变化。每次customerID发生更改时,都会有一个日志记录它过去是什么以及现在是什么。嗨,Gordon,1
从您的union all
的第一部分是什么?而且似乎列数不匹配?上述内容对我不起作用,它不会返回我问题中的最终结果:(谢谢!