I have the following table structure
Key int
MemberID int
VisitDate DateTime
How can group all the dates falling with a given date range say 15 days..The first visit for the sameMember should be considered as the starting date.
eg
Key ID VisitDate(MM/dd/YY)
1 1 02/01/11
2 1 02/09/11
3 1 02/12/11
4 1 02/17/11
5 2 02/03/11
6 2 02/19/11
In this case the result should be
ID StartDate EndDate
1 02/01/11 02/12/11
1 02/17/11 02/17/11
2 02/03/11 02/03/11
2 02/19/11 02/19/11
One way to do this would be to use window aggregating. Here’s how:
Setup:
Query:
Output:
Basically, for each row, the query is calculating the difference of days between
VisitDateand the firstVisitDatefor the sameIDand divides it by 15. The result is then used as a grouping criterion. Note that SQL Server uses integer division when both operands of the/operator are integers.