-2

Looking to get the "Total Consecutive Days" per row.

Shift Table Contains ShiftId, ClientID, ServiceId and ProviderID ShiftDetails Table has the dates.

There can be multiple Shifts with the same ShiftId, ClientID, ServiceId There can even be duplicate dates.

Would like to have multiple "Total Consecutive Days" calculations. Consecutive Days Per ClientID Consecutive Days Per ClientID and ServiceID Consecutive Days Per ClientID , ServiceID and ProviderID.

SQL Fiddle

monsey11
  • 243
  • 4
  • 18

1 Answers1

1

This is a gaps-and-islands problem. You can identify the islands by subtracting a sequence of integers from the date -- constant differences identify adjacent dates. Then use count(*) as a window function:

select t.*,
       count(*) over (partition by clientid, serviceid, dateadd(day, -seqnum, date)) as consecutive_days
from (select t.*,
             row_number() over (partition by clientid, serviceid order by date) as seqnum
      from t
     ) t
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786