求表中时间相减的SQL
按照USERID为标示,
USERID 相同的,下面的时间减上面的时间,作为上面时间的DUR值,以秒为单位
第一行的userid为1 的DUR为 2013-07-15 01:58:46.000 - 2013-07-15 01:52:43.000
数据量很大,希望得到一个效率比较高的SQL
[解决办法]
select id,userid,time_s,
datediff(ss,time_s,(select top 1 time_s from 表 where userid=a.userid and id>a.id order by id asc)) dur
from 表 a
[解决办法]
;with cte as (select id,userid,time_s,
datediff(ss,time_s,(select top 1 time_s from 表 where userid=a.userid and id>a.id order by id asc)) dur
from 表 a)
update 表
set dur=cte.dur
from 表 inner join cte on 表.userid=cte.userid
[解决办法]
update a set a.dur=datediff(mm,a.time_s,(select min(time_s) from tab where time_s>a.time_s and userid=a.userid)) from tab a