疾病提取SQL Server 2008中连续日期的查询检查

时间:2013-02-27 09:02:03

标签: sql-server

我的数据库(SQL Server 2008)中有一个表,其中包含以下列/ data。

 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

即,每个连续疾病期间返回一行

2 个答案:

答案 0 :(得分: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

这个奇妙的方法取自马丁史密斯的回答( link )并根据马丁的说法调整了这个例子,Itzik Ben Gan介绍了这个例子。

答案 1 :(得分: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