Considering the follwing:
CREATE TABLE Members (MemberID INT)
INSERT Members VALUES (1001)
CREATE TABLE PCPs (PCPID INT)
INSERT PCPs VALUES (231)
INSERT PCPs VALUES (327)
INSERT PCPs VALUES (390)
CREATE TABLE Plans (PlanID INT)
INSERT Plans VALUES (555)
INSERT Plans VALUES (762)
CREATE TABLE MemberPCP (
MemberID INT
, PCP INT
, StartDate DATETIME
, EndDate DATETIME)
INSERT MemberPCP VALUES (1001, 231, '2002-01-01', '2002-06-30')
INSERT MemberPCP VALUES (1001, 327, '2002-07-01', '2003-05-31')
INSERT MemberPCP VALUES (1001, 390, '2003-06-01', '2003-12-31')
CREATE TABLE MemberPlans (
MemberID INT
, PlanID INT
, StartDate DATETIME
, EndDate DATETIME)
INSERT MemberPlans VALUES (1001, 555, '2002-01-01', '2003-03-31')
INSERT MemberPlans VALUES (1001, 762, '2003-04-01', '2003-12-31')
I'm looking for a clean way to construct a timeline for Member/PCP/Plan relationships, where a change in either the PCP or plan for a member would result in a separate start/end row in the result. For example, if over a few years, a member changed their PCP twice and their plan once, but each on different dates, I would see something like the following:
MemberID PCP PlanID StartDate EndDate
1001 231 555 2002-01-01 2002-06-30
1001 327 555 2002-07-01 2003-03-31
1001 327 762 2003-04-01 2003-05-31
1001 390 762 2003-06-01 2003-12-31
As you can see, I need a separate result row for each date period that involves a difference in the Member/PCP/Plan association. I have a solution in place, but it is very convoluted with a lot of CASE statements and conditional logic in the WHERE clause. I'm just thinking there is a much simpler way to do this.
Thanks.