网络编程
位置:首页>> 网络编程>> 数据库>> Mysql 相邻两行记录某列的差值方法

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

作者:chenghaoyi6  发布时间:2024-01-18 22:29:14 

标签:Mysql,差值

表结构:

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

数据:

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 相邻两行记录某列的差值方法

来源:https://blog.csdn.net/ChengHaoYi6/article/details/52329833

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com