2013-02-27 58 views
0

我在我的數據庫(SQL Server 2008)中有一個包含以下列/數據的表。SQL Server 2008中連續日期的病症抽取查詢檢查

Emp ID  Start DT  End DT  Start Time  End Time  ABSTYPE  
20011664  13/02/2013  13/02/2013  09:00   17:00   Sick 
20011664  14/02/2013  14/02/2013  09:00   17:00   Sick 
20011664  15/02/2013  15/02/2013  09:00   17:00   Sick 
20011664  19/02/2013  19/02/2013  09:00   17:00   Sick 
20099999  14/02/2013  14/02/2013  09:00   17:00   Sick 

我想查詢將返回以下

20011664  13/02/2013  15/02/2013 09:00   17:00   Sick 
20011664  19/02/2013  19/02/2013 09:00   17:00   Sick 
20099999  14/02/2013  14/02/2013 09:00   17:00   Sick 

即返回一行連續疾病的各個時期

+0

你爲什麼要分開日期和時間?你已經嘗試過了什麼? – Paul 2013-02-27 09:05:35

+0

[SQL Server數據轉換]的可能重複(http://stackoverflow.com/questions/4630560/sql-server-data-conversion) – 2013-02-27 09:06:27

+0

在同一個月內從查詢中提取日期。檢查日期digfference等於1 – 2013-02-27 09:07:51

回答

0
;with cte as (
    select * 
    from [<YourTable>] 

    union all 

    select t.[Emp ID], t.[Start DT], t.[End DT] + 1, t.[Start Time], t.[End Time], t.[ABSTYPE] 
    from cte t 
    inner join [<YourTable>] d on t.[Emp ID] = d.[Emp ID] and t.[End DT] + 1 = d.[Start DT] 
), results as (
    select *, datediff(day, [Start DT], [End DT]) as daydiff, max(datediff(day, [Start DT], [End DT])) over (partition by [Emp ID], [Start DT]) as max_start_daydiff, max(datediff(day, [Start DT], [End DT])) over (partition by [Emp ID], [End DT]) as max_end_daydiff 
    from cte 
) 
select [Emp ID], [Start DT], [End DT], [Start Time], [End Time], [ABSTYPE] 
from results 
where daydiff = max_start_daydiff 
and daydiff = max_end_daydiff 
1

你可以這樣說:

CREATE TABLE #tbl ([Emp ID] INT,  [Start DT]  DATE, [End DT]  DATE, [Start Time] TIME, [End Time] TIME, ABSTYPE VARCHAR(100)) 
INSERT #tbl VALUES 
(20011664,  '13/02/2013' , '13/02/2013' , '09:00' ,  '17:00' ,  'Sick'), 
(20011664,  '14/02/2013' , '14/02/2013' , '09:00' ,  '17:00' ,  'Sick'), 
(20011664,  '15/02/2013' , '15/02/2013' , '09:00' ,  '17:00' ,  'Sick'), 
(20011664,  '19/02/2013' , '19/02/2013' , '09:00' ,  '17:00' ,  'Sick'), 
(20099999,  '14/02/2013' , '14/02/2013' , '09:00' ,  '17:00' ,  'Sick') 

;WITH a AS 
(
    SELECT * 
      , DATEDIFF(DAY, 0, [Start DT]) - 
       DENSE_RANK() OVER (PARTITION BY [Emp ID] ORDER BY DATEDIFF(DAY, 0, [Start DT])) 
       AS part 
    FROM #tbl 
) 

SELECT a.[Emp ID] 
     , MIN(a.[Start DT]) 
     , MAX(a.[End DT]) 
FROM a 
GROUP BY 
     a.[Emp ID], a.part 

這個美好的我thod是從馬丁史密斯的回答(link)並根據這個例子進行了調整,根據馬丁它是由Itzik本甘介紹。

+0

不錯。我認爲你可以通過使用'row_number()OVER(PARTITION BY [開發DT])'而不是'dense_rank()' – muhmud 2013-02-27 14:53:00

+0

來達到同樣的效果。使用'ROW_NUMBER'的情況下,使用'DENSE_RANK',以便正確處理關係,如果有兩行或更多行具有相等的[[Emp ID]和'[Start DT]',則會是tie。您可以通過插入一個先前插入的行來進行測試。 – 2013-02-27 15:08:33

+0

這是事情,在這種情況下,數據表明這不會發生。雖然很高興知道。 – muhmud 2013-02-27 17:37:07