Get the App
SLTechnology News&Howtos  ›  Database  › 

How to calculate the difference of a column between two adjacent rows in Mysql

Shulou Source: shulou.com Published: 2022-05-31 22:18:54 10月03日 Update

This article is about how to calculate the difference between two adjacent rows of records in Mysql. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

Table structure:

Data:

Demand:

According to the different grouping of company_id, the difference of touch_time of adjacent records of the same company_id is calculated respectively.

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

Results:

The above is how to calculate the difference between two adjacent rows of records in Mysql. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Differences more knowledge articles different practical the same that is work meetings data articles look knowledge points structure results industry details information channels follow Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Redmi Apple vpn Shulou Technology