Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query Help

Author  Topic 

lbeese
Starting Member

24 Posts

Posted - 2009-12-01 : 14:02:53
Hi,

I have unioned 2 tables - one that shows current enrollment and one that shows historical enrollment. This gives me the following (example):

Memberid Enrollmentdate Exitdate
123 2007-01-01 2007-12-31
123 2008-01-01 2008-12-31
123 2009-01-01 NULL
234 2007-01-01 NULL

I also have a "Case" table with:
memberid case_seq row_created
123 1 2009-07-05
234 1 2009-02-06

I am trying to pull the case information with only the enrollment record that was active when the case was created. I am having no luck. Any assistance is appreciated.

vijayisonly
Master Smack Fu Yak Hacker

1836 Posts

Posted - 2009-12-01 : 15:09:38
Can you show us the expected output for the sample data provided.
Go to Top of Page

lbeese
Starting Member

24 Posts

Posted - 2009-12-01 : 15:48:16
It would be:

case.memberid case.case_seq case.row_created enrollmentdate exitdate
123 1 2009-07-05 2009-01-01 NULL
234 1 2009-02-06 2007-01-01 NULL

Also, I realized that I didn't have an example where the case row created may occur along with an enrollment record that has an exit date.
Go to Top of Page

vijayisonly
Master Smack Fu Yak Hacker

1836 Posts

Posted - 2009-12-01 : 15:56:06
Sample Data

declare @member table (Memberid int,Enrollmentdate datetime,Exitdate datetime)
insert @member
select 123, '2007-01-01', '2007-12-31' union all
select 123, '2008-01-01', '2008-12-31' union all
select 123, '2009-01-01', NULL union all
select 234, '2007-01-01', NULL

declare @case table (memberid int, case_seq int,row_created datetime)
insert @case
select 123, 1, '2009-07-05' union all
select 234, 1, '2009-02-06'


Query...

SELECT b.memberid, 
b.case_seq,
b.row_created,
a.Enrollmentdate,
a.Exitdate
FROM (SELECT *,
row_number()
OVER(PARTITION BY Memberid ORDER BY Exitdate) AS rn
FROM @member) a
INNER JOIN @case b
ON a.Memberid = b.memberid
WHERE a.rn = 1
Go to Top of Page
   

- Advertisement -