Tsql 按时间间隔工作

Tsql 按时间间隔工作,tsql,sql-server-2008-r2,Tsql,Sql Server 2008 R2,我有一个tablebegin、end、typeid和时间间隔,类似这样: ... 14:10:44 14:15:51 1 14:12:33 14:18:42 2 15:24:09 15:24:17 1 ... ... 14:10:44 14:18:42 <-- as a result of merging 15:24:09 15:24:17 ... 有一些规则:id类型为2的间隔,id类型为1的间隔。 经过处理后,我得到如下结果: ... 14:1

我有一个tablebegin、end、typeid和时间间隔,类似这样:

...
14:10:44    14:15:51  1
14:12:33    14:18:42  2
15:24:09    15:24:17  1
...
...
14:10:44    14:18:42 <-- as a result of merging
15:24:09    15:24:17 
...
有一些规则:id类型为2的间隔,id类型为1的间隔。 经过处理后,我得到如下结果:

...
14:10:44    14:15:51  1
14:12:33    14:18:42  2
15:24:09    15:24:17  1
...
...
14:10:44    14:18:42 <-- as a result of merging
15:24:09    15:24:17 
...
是否存在处理此类数据的技术或方法?是否存在对时间间隔有用的表示


附带说明:SQL Server 2008 R2

要针对像您这样的数据编写代码真的很难。我在现实生活中见过好几次。这里有两个想法

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

我假设类型为_id 1的low始终是集合中的最低值。我还假设类型为_id1的行及其子行没有重叠集,因为这根本没有意义。

很难针对像您这样的数据进行编码。我在现实生活中见过好几次。这里有两个想法

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

我假设类型为_id 1的low始终是集合中的最低值。我还假设类型为_id1的行及其子行没有重叠集,因为这根本没有意义。

谢谢!这正是我决定问题的方式。。。但我有大约9个不同类型的ID,它们有不同的行为——它们可以拆分其他间隔,与其他类型的间隔合并,中间点等等。所以我的存储过程现在看起来像。。。M它看起来非常大:谢谢。我甚至认为它不是更好地将一个时间间隔表示为一组秒,并用它来处理一组行……我必须用测试数据和预期的输出来看待这个新问题!这正是我决定问题的方式。。。但我有大约9个不同类型的ID,它们有不同的行为——它们可以拆分其他间隔,与其他类型的间隔合并,中间点等等。所以我的存储过程现在看起来像。。。M它看起来非常大:谢谢。我甚至认为,将一个时间间隔表示为一组秒,并用它来处理一组行……我必须用测试数据和预期结果来看待这个新问题,不是更好吗