I have a table with positions of animals sorted by time and locations. I want to increment a counter when ever the location changes from one to the next ID. So each "Stay" of the animal should get an unique ID (Counter). I have a non-SQL description:
counter = 0
CASE (location at ID = location at ID-1) SET counter+1
I tried to use Dense_Rank() but failed to set the partition right. Here is a sample with the desired counter.
ID Location Counter
1 3 1
2 3 1
3 2 2
4 2 2
5 3 3
6 1 4
7 3 5
8 3 5
9 3 5
CREATE TABLE locations (idn serial PRIMARY KEY, location integer);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (2);
INSERT INTO locations (location ) VALUES (2);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (1);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (3);
INSERT INTO locations (location ) VALUES (3);