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
結果: