2013-09-23 93 views
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 

可以這樣不用循環呢?如果是這樣,?如何做呢?

+0

應該是什麼輸出? – TechDo

+0

@techdo:請在上面找到修改後的問題 –

+0

From和To列的數據類型是什麼? – TechDo

回答

0

爲什麼DUARTION是INT類型? 下面的查詢工會原始表有輸出GAPS查詢然後通過Date訂購此UNION和From

SQLFiddle demo

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] 
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]) 
+0

這工作。謝謝。但是,當表格有大量數據時,它肯定會達到性能。任何容易的拍攝? –