1

下面给出的是我拥有的一个表中的一组数据,有没有办法跟踪空闲时间?(例如 (11:00-12:00) 和 (18:45-19:15) 作为该日期的间隔)。

       Date           Activity  From     To    Duration
2013-09-09 00:00:00.000 Work    08:00   11:00   3.00
2013-09-09 00:00:00.000 Travel  12:00   13:00   1.00
2013-09-09 00:00:00.000 Work    13:00   15:00   2.00
2013-09-09 00:00:00.000 Work    15:00   18:00   3.00
2013-09-09 00:00:00.000 Travel  18:00   18:45   0.75
2013-09-09 00:00:00.000 Work    19:15   22:15   3.00

我期待像下面这样的东西

       Date           Activity  From     To    Duration
2013-09-09 00:00:00.000 Work    08:00   11:00   3.00
2013-09-09 00:00:00.000 Gap     11:00   12:00   1.00
2013-09-09 00:00:00.000 Travel  12:00   13:00   1.00
2013-09-09 00:00:00.000 Work    13:00   15:00   2.00
2013-09-09 00:00:00.000 Work    15:00   18:00   3.00
2013-09-09 00:00:00.000 Travel  18:00   18:45   0.75
2013-09-09 00:00:00.000 Gap     18:45   19:15   0.50
2013-09-09 00:00:00.000 Work    19:15   22:15   3.00

这可以在不循环的情况下完成吗?如果是这样,?怎么做到呢?

4

2 回答 2

0

请试试:

select
    [Date],
    Activity,
    [From],
    [To],
    CONVERT(varchar(5), CONVERT(Datetime,[TO])-CONVERT(Datetime,[FROM]), 108) Duration
From
(
    select 
        [Date],
        'Gap' Activity,
        [To] [From],
        (select top 1 d.[From] from YourTable d where CONVERT(datetime, d.[Date]+d.[From])>CONVERT(datetime, a.[Date]+a.[To]) order by CONVERT(datetime, d.[Date]+d.[From])) as [To],
        NULL as Duration
    from YourTable a
    where 
        (select COUNT(*) from YourTable b where CONVERT(datetime, b.[Date]+b.[From])=CONVERT(datetime, a.[Date]+a.[To]))=0

    union all

    select * From YourTable
)x 
where 
    [To] IS NOT NULL
order by CONVERT(datetime, x.[Date]+x.[From])
于 2013-09-23T14:11:04.247 回答
0

为什么是DUARTIONINT 类型?以下查询将原始表与输出 GAPS 的查询联合起来,然后通过Date和排序此 UNIONFrom

SQLFiddle 演示

SELECT 
Date,
Activity,
[FROM],
[TO],
CONVERT(varchar(5),
CONVERT(Datetime,[TO],108)-
CONVERT(Datetime,[FROM],108)
,108) as Duration


 FROM
(
select Date,Activity,[From],[To] from T
UNION ALL
select Date,'GAP' as Activity, [To] as [From],
(select TOP 1 T.[From] from T where T.Date=T1.Date
                          and T.[From]>T1.[To] 
                          order by T.[From])
as [To]


from T as T1
where NOT EXISTS (select 1 from T where T.Date=T1.Date 
                                    and T.[From]=T1.[To]) 
      and EXISTS (select 1 from T where T.Date=T1.Date 
                                    and T.[From]>T1.[To])  

) T2
ORDER BY Date,[FROM]
于 2013-09-23T14:05:37.633 回答