这个反应不是关于 CTE,而是关于让你找到解决这个特定问题的方法。这里不需要递归。只有当您必须多次迭代指向自身的链接时,才需要递归。如果您想学习 CTE,请尝试制作例如器官图。
您的解决方案是将 EffectiveDate 作为 Opendate 链接到另一个 EffectiveDate 作为 Closedate(如果有的话)。
首先,您可能希望使用带有分区的 ROW_NUMBER() 函数为每个实体创建一个位置索引。所以我的新表location 将被定义为
SELECT ROW_NUMBER() OVER (partition BY EntityId ORDER BY EntityEffectiveDate ASC) as LocId,
EntityId, EntityLocation, EntityEffectiveDate
INTO Location
FROM YourOldEntityLocation
现在您可以将每个位置的有效日期(相等的 entityId)链接到该位置的下一个有效日期 (LocId+1),如果有的话(左连接)。
SELECT opendate.LocId, opendate.EntityId, opendate.EntityLocation, opendate.EntityEffectiveDate,
isnull(closedate.EntityEffectiveDate,'2050-01-01') as EffectiveToDate
FROM Location as opendate
LEFT JOIN Location as closedate
ON closedate.entityId = opendate.entityId
AND opendate.LocId+1 = closedate.LocId
ORDER BY opendate.EntityId, EntityEffectiveDate DESC
结果:
LocId EntityId EntityLocation EntityEffectiveDate EffectiveToDate
3 10170 63 2011-01-01 2050-01-01
2 10170 31 2006-01-01 2011-01-01
1 10170 43 2003-07-01 2006-01-01
3 11674 45 2014-07-01 2050-01-01
2 11674 29 2004-10-01 2014-07-01
1 11674 45 2003-04-01 2004-10-01
3 11675 45 2011-04-01 2050-01-01
2 11675 29 2004-10-01 2011-04-01
1 11675 45 2003-04-01 2004-10-01
根据您的要求。
这可能是一个建议,根本不要替换 NULL 值。根据@Jack 的反应,您不必幻想未来的约会。简单的结果告诉您此 EntityLocation 没有关闭状态。
通过在此列中选择 NULL 值来选择实际位置很简单。结果是:
LocId EntityId EntityLocation EntityEffectiveDate EffectiveToDate
3 10170 63 2011-01-01 NULL
2 10170 31 2006-01-01 2011-01-01
1 10170 43 2003-07-01 2006-01-01
3 11674 45 2014-07-01 NULL
2 11674 29 2004-10-01 2014-07-01
1 11674 45 2003-04-01 2004-10-01
3 11675 45 2011-04-01 NULL
2 11675 29 2004-10-01 2011-04-01
1 11675 45 2003-04-01 2004-10-01