sql 求相邻两行的时间间隔

xyzmrsir 2016-05-10 08:23:40


请问怎么求相邻两行的时间间隔(单位为秒)

网上查到了lag、lead、DateDiff 函数
...全文
732 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
shoppo0505 2016-05-11
  • 打赏
  • 举报
回复
原表中每一行数据连接下一行数据 你直接select看一下就好了
xyzmrsir 2016-05-11
  • 打赏
  • 举报
回复
引用 2 楼 shoppo0505 的回复:
with m as ( select '6:05:18' a union all select '6:05:28' union all select '6:05:38' union all select '6:05:48' ) , tb as ( select _Index = ROW_NUMBER()over(order by a) ,* from m ) select DATEDIFF(second, a.a,b.a) AS DIFF from tb a inner join tb b on b._Index = a._Index + 1
木有看懂。。。。求大虾解释下,非常感谢!
xyzmrsir 2016-05-11
  • 打赏
  • 举报
回复
引用 楼主 xyzmrsir 的回复:
请问怎么求相邻两行的时间间隔(单位为秒) 网上查到了lag、lead、DateDiff 函数
我的是sql2014的,刚试过可以用lag和lead的,怎么求时间间隔呢? datediff 不能对两列求时间插值。。。。 非常感谢!
xyzmrsir 2016-05-11
  • 打赏
  • 举报
回复
引用 1 楼 wmxcn2000 的回复:
lag、lead 这两个函数是oracle 的用法。sql server 不支持的;

with m as (
select '6:05:18' a union all
select '6:05:28' union all
select '6:05:38' union all
select '6:05:48' 
)
-- prev 是上一个行的时间 ,你再减一下就可以了
select a , (select top 1 a from m n where m.a > n.a order by a desc) prev
 from m

a       prev
------- -------
6:05:18 NULL
6:05:28 6:05:18
6:05:38 6:05:28
6:05:48 6:05:38

(4 行受影响)


我的是sql2014的,刚试过可以用lag和lead的,怎么求时间间隔呢? datediff 不能对两列求时间插值。。。。 非常感谢!
shoppo0505 2016-05-10
  • 打赏
  • 举报
回复
with m as ( select '6:05:18' a union all select '6:05:28' union all select '6:05:38' union all select '6:05:48' ) , tb as ( select _Index = ROW_NUMBER()over(order by a) ,* from m ) select DATEDIFF(second, a.a,b.a) AS DIFF from tb a inner join tb b on b._Index = a._Index + 1
卖水果的net 版主 2016-05-10
  • 打赏
  • 举报
回复
lag、lead 这两个函数是oracle 的用法。sql server 不支持的;

with m as (
select '6:05:18' a union all
select '6:05:28' union all
select '6:05:38' union all
select '6:05:48' 
)
-- prev 是上一个行的时间 ,你再减一下就可以了
select a , (select top 1 a from m n where m.a > n.a order by a desc) prev
 from m

a       prev
------- -------
6:05:18 NULL
6:05:28 6:05:18
6:05:38 6:05:28
6:05:48 6:05:38

(4 行受影响)


34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧