2011-07-18 299 views
1

我有一个表(开始,结束,typeid的)在一定时间间隔,这样做某件事情:在一定时间间隔

... 
14:10:44 14:15:51 1 
14:12:33 14:18:42 2 
15:24:09 15:24:17 1 
... 

有一些规则:区间型ID 2个intersepts 1型的间隔。 而且处理后,我得到这样的:

... 
14:10:44 14:18:42 <-- as a result of merging 
15:24:09 15:24:17 
... 

是否存在任何tehnics或方法这样的数据?可能存在时间间隔的任何有用表示吗?

P.S. SQL Server 2008 R2

回答

1

真的很难针对像你这样的数据进行编码。在现实生活中我已经看过几次了。这里有两个想法。

declare @t table(low time, high time, type_id tinyint) 

insert @t values('14:10:44','14:15:51', 1) 
insert @t values('14:12:33','14:18:42', 2) 
insert @t values('15:24:09','15:24:17', 1) 

select low, coalesce(a.high, t.high) high 
from @t t 
cross apply (select min(high) high 
from @t t2 
where high > t.high and type_id = 2 
and not exists (select 1 from @t 
where t2.high between low and high and type_id = 2 and not 
(t2.high = high and t2.low = low))) a 
where type_id = 1 

这是另一种方法。根据您的数据,甚至可能会更好。

;with cte as 
(
select low low2, high, low 
from @t where type_id = 1 
union all 
select cte.high, t.high, cte.low 
from @t t 
join cte on cte.high > t.low 
and cte.high < t.high 
where t.type_id = 2 
) 
select low, max(high) high from cte group by low 

我假设低与type_id 1总是最低的集合。我还假设没有重叠的行与type_id 1(及其子行),因为这将是没有意义的。

+0

谢谢!这正是我决定这个问题的原因......但我有大约9个defernt type id,他们有不同的行为 - 他们可以拆分其他间隔,合并其他类型的间隔,交叉等等。所以我的存储过程现在看起来像... m ...它看起来很大:о)。我甚至认为它不会更好地代表一个时间间隔作为一组秒,并与它一起工作如何一组行... –

+0

我必须看到与测试数据和预期结果的新问题 –