求一按条件筛选行进行统计的SQL语句(有点难度)
表内容如下:
starttime               status
2013-03-04 09:09:02	1
2013-03-04 15:01:15	5
2013-03-04 15:05:17	1
2013-03-04 15:28:01	5
2013-03-04 15:29:57	1
2013-03-04 15:34:36	5
我想查出所有status=1和其starttime的时间最相近的一条status=5的之间的时间长度。望高手帮忙想想
              
              
------解决方案--------------------如果你这格式1与5是一一按时间对应的话那就好办了
select a.starttime,b.starttime,DATEDIFF(D,a.starttime,b.starttime)
from (select starttime,row_number() over(order by starttime) rn from tb where status=1)a 
left join 
(select starttime,row_number() over(order by starttime) rn from tb where status=5)b 
on a.rn=b.rn
------解决方案--------------------select a.starttime,b.starttime,DATEDIFF(D,a.starttime,b.starttime)
from (select starttime,
(select count(1) from tb where status=1 and starttime<=t1.starttime) rn from tb t1 where status=1)a 
left join 
(select starttime,
(select count(1) from tb where status=5 and starttime<=t1.starttime) rn from tb where status=5)b 
on a.rn=b.rn