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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With