0

我的数据库(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

即,为每个连续生病的时期返回一行

4

2 回答 2

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

这个奇妙的方法取自 Martin Smith 的答案(链接)并针对这个例子进行了调整,根据 Martin 的说法,它是由 Itzik Ben Gan 介绍的。

于 2013-02-27T13:17:39.283 回答
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
于 2013-02-27T09:51:58.073 回答