Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find rows that have specific difference between two rows

Consider the table

ID     Value
1       3
2       4
3       6
4       7
5       8
6      11
7      12

I want to find rows where the difference between two subsequent Values is different than 1.

Id = 2 has Value = 4 and Id = 3 has Value = 6, difference in Value between these two rows is 2, which is different than 1. As a return I want this table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Id    Difference
2     2
5     3

I am using MySQL (SQL available at cPanel).

I could not find a solution to this problem anywhere.

>Solution :

This is easily solved by using lead or lag windows:

with diff as (
  select * , Abs(value -  lead(value) over(order by id)) diff
  from t
)
select *
from diff
where diff > 1;

See Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading