Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql group by difference to previous row

I have some sorted values (called point) that must be group together based on their difference to the previous row like in the following example.

In this example a new group is started when the difference of the point to the previous one is greater than 10.

point   group
  1     1
  2     1
  3     1
101     2
103     2
105     2
213     3
214     3
215     3

Using the lag window function I can calculate the difference between the points but I'm missing the part to build the groups like in the example above.

Any help is appreciated, thank you!

like image 762
Florian Gutmann Avatar asked Sep 15 '25 17:09

Florian Gutmann


1 Answers

select point, sum(inc) over (order by point)+1 as group
from (
    select point, 
    (case when point-lag(point,1) over (order by point) > 1 then 1 else 0 end)  inc
    from whatevertable
) base
order by point

there may be a way to do it without a sub-select, but this is what I came up with.

like image 182
Joe Love Avatar answered Sep 18 '25 06:09

Joe Love