本篇文章给大家分享的是有关怎么在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://www.0818zz.com