Mysql 相邻两行记录某列的差值方法

表结构:

数据:

需求:

按照company_id不同分组,然后分别求出相同company_id相邻记录touch_time的差值

SQL:

select r1.company_id,
 r1.touch_time,
 r2.touch_time,
 r1.touch_time - r2.touch_time
 from (select (@rownum := @rownum + 1) as rownum,
  info.company_id,
  info.touch_time
  from sys_touch_info info, (select @rownum := 0) r
  where info.touch_time is not null
  order by info.company_id) r1
 left join (select (@index := @index + 1) as rownum,
   info.company_id,
   info.touch_time
  from sys_touch_info info, (select @index := 0) r
  where info.touch_time is not null
  order by info.company_id) r2
 on r1.company_id = r2.company_id
 and r1.rownum = r2.rownum - 1

结果:

以上这篇Mysql 相邻两行记录某列的差值方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。