计算指定时间前后时差的SQL

求一个计算指定时间前后时差的SQL
需求是这样的,有下图这样一张表,按USERID分组 ,获取 SENSORID =15 的这个时间的前后时间相邻的两个时间 
按以下格式输出   USERID   StartTime(前一时间)   CurrentTime(SENSORID=15的时间 )   StopTime (后一时间 ) ,求大神支招计算指定时间前后时差的SQL
------解决方案--------------------
根据你前9行数据,写了个例子,数据圈选出来了,行列转化自己弄了。
with tb(userid, checketime, sensorid) as 
(
select 299, '29.07.2014 07:33:41',4 union all
select 299, '29.07.2014 09:19:23',6 union all
select 299, '29.07.2014 09:29:09',4 union all
select 299, '29.07.2014 10:54:25',6 union all
select 299, '29.07.2014 11:11:53',15 union all
select 299, '29.07.2014 12:52:32',5 union all

select 299, '29.07.2014 15:58:46',6 union all
select 317, '29.07.2014 11:06:38',15 union all
select 333, '29.07.2014 07:43:26',4
)

, tempdata as
(
select
ROW_NUMBER() over(order by userid, checketime) as rownumber
,*
from tb
)
, tempdata2 AS
(
select * from tempdata
where sensorid = 15
)
select 
tempdata.* 
from tempdata
inner join tempdata2 
on tempdata2.rownumber = tempdata.rownumber + 1
or tempdata2.rownumber = tempdata.rownumber - 1
or tempdata2.rownumber = tempdata.rownumber

------解决方案--------------------

with tb as(select * from 你的表名)
,tc as(
select * from tb a where SENSORID=15)
select * from tc union all
select * from tb a where checktime=(select MAX(checktime) from tb 
where a.userid=userid and checktime<(select checktime from tc 
where a.userid=userid)) union all
select * from tb a where checktime=(select min(checktime) from tb 
where a.userid=userid and checktime>(select checktime from tc 
where a.userid=userid))
order by 1,2


------解决方案--------------------
select userid,CurrentTime=(select a.checktime from tb a where a.userid=b.userid and a.sensorid=15),
StartTime=(select max(c.checktime) from tb c where c.userid=b.userid and c.checktime<(select a.checktime from tb a where a.userid=b.userid and a.sensorid=15)),
StopTime =(select min(c.checktime) from tb c where c.userid=b.userid and c.checktime>(select a.checktime from tb a where a.userid=b.userid and a.sensorid=15))
from tb b
group by userid

------解决方案--------------------
引用:
Quote: 引用:

select userid,CurrentTime=(select a.checktime from tb a where a.userid=b.userid and a.sensorid=15),
StartTime=(select max(c.checktime) from tb c where c.userid=b.userid and c.checktime<(select a.checktime from tb a where a.userid=b.userid and a.sensorid=15)),
StopTime =(select min(c.checktime) from tb c where c.userid=b.userid and c.checktime>(select a.checktime from tb a where a.userid=b.userid and a.sensorid=15))
from tb b
group by userid



消息 512,级别 16,状态 1,第 2 行
子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。

每组15的不是唯一?