2012-03-30 70 views
2

我在緩慢變化的維度類型II中選擇時遇到問題。我期望選擇一個員工技能認證的實際長度,以便我可以在報告中顯示他的認證的開始和結束。你會怎麼做呢?下面我列出了員工'80844'的記錄圖像,並在記錄下面顯示了預期結果。從緩慢變化的維度類型II中進行選擇

我正在使用Microsoft SQL Server 2008 R2。

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

+0

什麼類型的DB您使用的是? – 2012-03-30 09:17:57

+0

我正在使用Microsoft SQL Server 2008 R2。 – 2012-03-30 09:29:26

+1

我不明白結果如何確定。爲什麼在結果的第一行結束日期2012-04-01? – fancyPants 2012-03-30 10:18:14

回答

0

謝謝你有趣的問題。這是衆所周知的'缺口和島嶼'問題。你可以閱讀更多關於它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 
+0

謝謝,這很好。這正是我正在尋找的 – 2012-04-02 09:36:38

相關問題