读书人

求表中时间相减的SQL,该如何解决

发布时间: 2013-07-16 22:38:05 作者: rapoo

求表中时间相减的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

[解决办法]
引用:
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))

读书人网 >SQL Server

热点推荐