Link to home
Start Free TrialLog in
Avatar of jvoconnell
jvoconnell

asked on

determine if date is consecutive by person ID

Experts,

I have a table with a member id and an eligibility date. I need to create a record by member id with the minimum eligibility date and max eligibility date where the dates are consecutive (by month). The logic is also that there can be be a one month gap to be considered "consecutive". When the dates aren't consecutive, it would be a new record.

MemberID        EligibilityDT
-----------------------------------------
XYZ                         1/1/2014
XYZ                         2/1/2014
XYZ                        4/1/2014
XYZ                        7/1/2014

The desired output would be:

MemberID      StartDT       EndDT
-----------------------------------------------
XYZ                1/1/2014      4/1/2014
XYZ               7/1/2014        7/1/2014


My logic is cursor processing. I am looping thru by member and comparing a date variable to the next date variable by DateDiff. Then swithcing the value of the date variable vs. the next date.

Am I  even correct that cursor processing is the way to go. It just seems like there has to be an easier way.
The table has 10M rows. Any insight is appreciated.

SQL Server 2012 if that matters.

Thank you.
Avatar of PortletPaul
PortletPaul
Flag of Australia image

SQL Server 2012 if that matters = thank you, thank you, thank you - knowing version is always important
ASKER CERTIFIED SOLUTION
Avatar of chaau
chaau
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
LEAD() LAG() were introduced at SQL 2012 so  it was worth knowing.

Well done chaau!

--
just in case: no points please
Avatar of jvoconnell
jvoconnell

ASKER

Wow! This is great. I new I was attacking this the wrong way. Thank you so much!!  Thank you both for jumping in.
Thanks for that. I am curious how performant the query is. Have you tried against your 10M records? How fast was it?
Performance is awesome! We decided to go back even further in history. We have 24M rows and the query finished in 22 seconds. My cursor logic was running at @ 3 hours for a small sampling of data. THANK YOU AGAIN!
Thanks for the feedback.

Take it as a lesson to use "set based" operations in SQL whenever you can and use cursors only where they are absolutely the only option :)

Cheers, Paul