2012-08-07 56 views
-1
Create table #job(id int,start_time datetime,end_time datetime) 

insert into #job values(1,'2012-08-06 11:30:00.000','2012-08-06 15:30:00.000') 
insert into #job values(1,'2012-08-06 15:30:00.000','2012-08-06 16:30:00.000') 
insert into #job values(2,'2012-08-06 16:30:00.000','2012-08-06 17:30:00.000') 
insert into #job values(1,'2012-08-06 17:30:00.000','2012-08-06 18:30:00.000') 

我所需要的数据如下,我需要仅具有ID = 1个请求用于查询

回答应该是这样的下方。

1 '2012-08-06 11:30:00.000' '2012-08-06 16:30:00.000' 
1 '2012-08-06 17:30:00.000' '2012-08-06 18:30:00.000' 

回答

0

试试这个:

select j1.id,min(j1.start_time) start_time,max(j2.end_time) end_time from #job j1 inner join #job j2 
on j1.id=j2.id and j1.end_time = j2.start_time 
group by j1.id 

union 

select * from #job where start_time not in(

select start_time from #job where start_time in(
select j1.start_time from #job j1 inner join #job j2 
on j1.id=j2.id and j1.end_time = j2.start_time and j1.id=1) 

union all 

select start_time from #job where start_time in(
select j1.end_time from #job j1 inner join #job j2 
on j1.id=j2.id and j1.end_time = j2.start_time and j1.id=1) 
) 

and id=1 
+0

非常感谢AnandPhandke – user1581498 2012-08-07 12:15:01

+0

如果它有用,你可以接受的答案。 – AnandPhadke 2012-08-07 12:37:13