下面给出的是我所拥有的一个表中的一组数据,有没有办法跟踪空闲时间? (例如(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 :(得分:0)
为什么DUARTION
是INT类型?
以下查询联合原始表与输出GAPS的查询然后按Date
和From
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]
答案 1 :(得分: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])