Мне удалось получить желаемый результат с помощью рекурсивного cte. UPI - это естественный ключ. Однако на самом деле события происходят из отдельного файла, который поворачивается и присоединяется к измерению. (BLI003) было 2 строки, поскольку у него было два события. sql был следующим:
CREATE TABLE #tstDimPortfolio
(
[ID][INT] IDENTITY (1,1) NOT NULL,
[UPI] [varchar](20) NOT NULL,
[MF_CODE] [varchar](10) NULL,
[BH_Code] [varchar](10) NULL,
[CR_Code] [varchar](10) NULL,
[ValidFrom][varchar](10) NOT NULL,
[ValidTo][varchar](10) NULL,
[IsCurrent] [CHAR] (1) NULL,
[DateofChange] [varchar](10) NULL,
[LookupMF_CODE] [varchar](10) NULL,
[LookupBH_Code] [varchar](10) NULL,
[LookupCR_Code] [varchar](10) NULL,
)
INSERT INTO #tstDimPortfolio
SELECT 'B06531','B06531','','B06531','20111230',NULL,'Y','20120101','','B06531', ''UNION ALL
SELECT 'BLI003','','BLI003','BBL_WORLD','20111230',NULL,'Y','20120102','BLI004','', ''UNION ALL
SELECT 'BLI003','','BLI003','BBL_WORLD','20111230',NULL,'Y','20120103','','BLI005', ''UNION ALL
SELECT 'BLI027','BLI027','L147','BBL_GBN','20111230',NULL,'Y','20120104','','L146', ''
SELECT ROW_NUMBER() OVER (PARTITION BY UPI ORDER BY UPI, DateofChange) Sequence,
UPI,
CASE WHEN LookupMF_CODE <> '' THEN LookupMF_CODE ELSE MF_CODE END MF_CODE,
CASE WHEN LookupMF_CODE <> '' THEN LookupBH_Code ELSE BH_Code END BH_Code,
CASE WHEN LookupCR_Code <> '' THEN LookupCR_Code ELSE CR_Code END CR_Code,
ValidFrom, ValidTo, IsCurrent, DateofChange,
LookupMF_CODE,
LookupBH_CODE,
LookupCR_CODE
INTO #Dimension_Table
FROM #tstDimPortfolio
;WITH AddedDim AS
(SELECT * FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY UPI ORDER BY UPI, DateofChange) Sequence,
UPI,
CASE WHEN LookupMF_CODE <> '' THEN LookupMF_CODE ELSE MF_CODE END MF_CODE,
CASE WHEN LookupBH_CODE <> '' THEN LookupBH_Code ELSE BH_Code END BH_Code,
CASE WHEN LookupCR_Code <> '' THEN LookupCR_Code ELSE CR_Code END CR_Code,
DateofChange AS ValidFrom,
ValidTo,
IsCurrent
FROM #tstDimPortfolio
)A
WHERE SEQUENCE = 1
UNION ALL
SELECT
DT.Sequence
, DT.UPI
,CASE WHEN DT.LookupMF_CODE <> '' THEN DT.LookupMF_CODE ELSE DM.MF_CODE END MF_CODE
,CASE WHEN DT.LookupBH_CODE <> '' THEN DT.LookupBH_Code ELSE DM.BH_Code END BH_Code
,CASE WHEN DT.LookupCR_Code <> '' THEN DT.LookupCR_Code ELSE DM.CR_Code END CR_Code
,DT.DateofChange AS ValidFrom
,DT.ValidTo
,DT.IsCurrent
FROM #Dimension_Table dt inner join
AddedDim dm
on DT.UPI = DM.UPI
AND dt.Sequence = DM.Sequence + 1
)
ВЫБРАТЬ *
INTO #temp
FROM AddedDim