It seems that this is the expected behaviour as per the SQL standard. I had to write a function to achieve what I wanted for it to do - which is first order by date, then partition. This means that the counter is reset every time a number other then the same is present.
This was very useful for a consecutive day streak.
Code to my function:
CREATE TYPE consecutive_length_type AS
(daystreak integer,
streakstart date,
streakend date;
CREATE OR REPLACE FUNCTION get_maxconsecutive_day_streak() RETURNS consecutive_length_type AS
$BODY$
declare
max_length integer := 0;
end_date date;
cons_days integer :=0;
return_rec consecutive_length_type;
rec record;
begin
for rec in
select * from table t --table as above
loop
if rec.no_of_days_between = 1 then
cons_days := cons_days + 1 ;
if cons_days > max_length then
max_length := cons_days;
end_date := rec.enddate ;
--this way I can see when the streak ended
end if;
else
cons_days := 0;
end if;
end loop;
return_rec.daystreak := max_length;
return_rec.streakend := end_date;
return_rec.streakstart := end_date - max_length;
--I am calculating the day start so I can use it further on
return return_rec;
end;
$BODY$
LANGUAGE plpgsql ;
What I originally have is a table of id mapped to date. In order to compute the no of days between the two consecutive days I run this query:
select id ,
lag(date_logged,1,date_logged) over
(partition by id order by id, date_logged ) as startdate
date_logged as enddate ,
date_logged- lag(date_logged,1,date_logged) over
(partition by id order by id, date_logged ) as no_of_days_between
from table_name;