This is my table:
employeeid workdate workstatus
----------- ----------------------- ----------
1 2020-09-01 00:00:00.000 ON
1 2020-09-02 00:00:00.000 ON
1 2020-09-03 00:00:00.000 ON
1 2020-09-04 00:00:00.000 OFF
1 2020-09-05 00:00:00.000 OFF
2 2020-09-01 00:00:00.000 ON
2 2020-09-02 00:00:00.000 ON
2 2020-09-03 00:00:00.000 OFF
2 2020-09-04 00:00:00.000 OFF
2 2020-09-05 00:00:00.000 ON
And I am executing this query:
select employeeid, workdate, workstatus, rank() over(partition by employeeid, workstatus order by workdate) as cycle
from #workstatus
order by 1, 2
With this result:
employeeid workdate workstatus cycle
----------- ----------------------- ---------- --------------------
1 2020-09-01 00:00:00.000 ON 1
1 2020-09-02 00:00:00.000 ON 2
1 2020-09-03 00:00:00.000 ON 3
1 2020-09-04 00:00:00.000 OFF 1
1 2020-09-05 00:00:00.000 OFF 2
2 2020-09-01 00:00:00.000 ON 1
2 2020-09-02 00:00:00.000 ON 2
2 2020-09-03 00:00:00.000 OFF 1
2 2020-09-04 00:00:00.000 OFF 2
2 2020-09-05 00:00:00.000 ON 3
My goal is to have the "cycle" of on/off work be identified by a unique number per employee. So the three ON days for employee 1 would be cycle 1, then the two OFF days would be cycle 2.
The first two ON days for employee 2 would be cycle 1, then the two OFF days would be cycle 2, and the final ON day would be cycle 3.
I'm not sure if I can use RANK() for this, or if there is a better solution. Thanks!