I currently have a query that returns, for example, the following: (You can assume that this is what the table structure looks like)
customer_id | start_date | end_date
1 | 20120101 | 20120401
2 | 20120402 | 20121231
1 | 20130101 | 20130401
1 | 20130101 | 20130330
2 | 20130331 | 99991231
2 | 20130402 | 99991231
There's two points to consider:
- A Customer can come back, so doing a normal max/min approach on this doesn't work.
- This is actually an overview of multiple services, and sometimes one of them starts or ends in a different date. (Very uncommon, but I need to deal with this scenario.)
So taking the above into account, I want a query that will return the 1st, 2nd, 3rd, and 5th lines.
My idea & approach to this would be:
- If start_dates are equal, display the max end date. (group by customer_id & start_date, max(end_date))
- If end_dates are equal, display the min start date. (group by customer_id & end_date, min(start_date))
I can write a query that will do one of the above, but I'm not sure how I'd be able to go about doing both of them at the same time. Or if a different approach altogether would be better.
SQL Server 2008
Thank you!