从缓慢变化的尺寸类型II中选择

时间:2012-03-30 07:51:04

标签: sql type-2-dimension

我遇到了一个缓慢变化的尺寸类型II选择的问题。我希望选择员工技能认证的实际长度,以便我可以在报告中显示其认证的开始和结束。你会怎么做呢?下面我已经包含了员工'80844'记录的图像,并且记录了预期结果。

我使用的是Microsoft SQL Server 2008 R2。

Records an employee 80844 and the expected result needed to display his certification

1 个答案:

答案 0 :(得分:2)

感谢您提出有趣的问题。这是众所周知的“差距和岛屿”问题。您可以阅读更多相关信息there

对于您的案例,解决方案可能如下所示:

    create table #tmp 
       (
         dimEmployeeID int not null,
         EmployeeNumber int not null,
         Start datetime not null,
         [End] datetime not null,
         SkillID int not null
       )


   insert into #tmp values
     (386 , 80844, '1900-01-01', '2012-02-28', 14),
     (1172, 80844, '2012-02-29', '2012-02-29', 14),
     (1173, 80844, '2012-03-01', '2012-04-01', 14),
     (1175, 80844, '2012-04-06', '2012-04-12', 14),
     (1176, 80844, '2012-04-13', '2012-04-21', 14),
     (1172, 80844, '2012-02-29', '2012-02-29', 87),
     (1173, 80844, '2012-03-01', '2012-04-01', 87),
     (1174, 80844, '2012-04-02', '2012-04-05', 87),
     (1175, 80844, '2012-04-06', '2012-04-12', 87)

   ;with StartingPoints as
   (
     SELECT EmployeeNumber, SkillID, Start, ROW_NUMBER() OVER(partition by EmployeeNumber,    SkillID order by Start asc) AS rn
     FROM #tmp AS A
     WHERE NOT EXISTS
       (
         SELECT 1
         FROM #tmp AS B
         WHERE 
           A.EmployeeNumber = B.EmployeeNumber
           and A.SkillID = B.SkillID
           and A.Start - 1 = B.[End]
        )
   ),
   EndingPoints AS
   (
     SELECT EmployeeNumber, SkillID, [End], ROW_NUMBER() OVER(partition by EmployeeNumber,    SkillID order by Start asc) AS rn
     FROM #tmp AS A
     WHERE NOT EXISTS
       (
         SELECT 1
         FROM #tmp AS B
         WHERE 
           A.EmployeeNumber = B.EmployeeNumber
           and A.SkillID = B.SkillID
           and A.[End] + 1 = B.Start
        )
   )
   SELECT S.EmployeeNumber, S.SkillID, S.Start, E.[End]
   FROM StartingPoints AS S
     JOIN EndingPoints AS E
   ON 
     S.EmployeeNumber = E.EmployeeNumber
     and S.SkillID = E.SkillID
     and S.rn = E.rn