5

I have a table with Point geometries representing GPS data of participants. I am calculating the distance between two consecutive points:

SELECT id, participant, ST_Distance(geom, lag(geom, 1) OVER (ORDER by id ASC))
FROM table;

but I would like to do the calculation separately for each participant, so instead of:

id;participant;distance
1;1;NULL
2;1;dist(1,2)
3;1;dist(2,3)
4;2;dist(3,4)
5;2;dist(4,5)
6;2;dist(5,6)

I would like to get

id;participant;distance
1;1;NULL
2;1;dist(1,2)
3;1;dist(2,3)
4;2;NULL
5;2;dist(4,5)
6;2;dist(5,6)

1 Answer 1

5

You can use partition by in your window:

SELECT 
  id, 
  participant, 
  ST_Distance(geom, lag(geom, 1) OVER (PARTITION BY participant ORDER by id ASC))
FROM table;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.