日期:2014-05-17  浏览次数:20396 次

求表中时间相减的SQL
本帖最后由 u010962314 于 2013-07-15 17:36:23 编辑

按照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

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

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 的有吗 ?
我想用join连接写,,写不出来。。。


update 表 set dur=datediff(ss,time_s,(select top 1 time_s from 表 where userid=a.userid and id>a.id order by id asc))