ID dateandtime EmailID 73 6/8/2014 00:00:00 2 74 6/9/2014 00:00:00 2 75 6/10/2014 00:00:00 2 76 6/11/2014 00:00:00 2 77 6/12/2014 00:00:00 2 78 6/13
This is an example of identifying groups of things that occur in order. In this case, the groups are in order by date and you want consecutive dates.
You can find the group by using the different in two sequential values. Enumerate the values by date. Then enumerate the values by date and emailId
. The difference is a constant for sequential values with the same emailId
. Here is how it would work in your case:
select min(TheDate) as StartDate, max(TheDate) as EndDate, emailId
from (select t.*,
dateadd(day, - row_number() over (order by TheDate), theDate) as grp
from table t
) t
group by grp, emailId;