I am trying to count the number of consecutive weeks an employee went to work. So I have this table that has whether jon or andy went to work on certain weeks (I have all week of the year).
I am trying on Postgresql
What I would like know the number of times each person went consecutively to work x number of weeks.
So the way the below is read is that Andy went twice two consecutive weeks.
I feel like I am close. On python I could use a for loop probably, but on Postgresql I am a bit lost.
Thanks!
2
Answers
We group each amount of consecutive weeks worked per person and then group by the result and the person.
Fiddle
You can find groups of weeks where a person was present, assigning a running
id
to each row of the group, and then apply acount
on the results, performing agroup by
on theid
:See fiddle.