quote: Originally posted by stamford
quote: Originally posted by James K
SELECT PLAN_ID FROM( SELECT PLAN_ID, ROW_NUMBER() OVER (PARTITION BY CARE_ID ORDER BY AGREE_DATE, PLAN_ID) AS RN FROM YourTable) s WHERE RN = 1;
I'm not so sure that works, because when I run the script it doesn't return, for instance, PLAN_ID 42 which has the earliest PLAN_AGREED_DATE of 01/09/2009 for CARE_ID 5 ?
I created test data with the sample in your original posting, and used the code I posted earlier. See the results in green below. It does pick up 42 for care_id = 5create table #tmp (PLAN_ID INT, CARE_ID INT, N5_3_PLAN_AGREE_DATE SMALLDATETIME);SET DATEFORMAT DMY;insert into #tmp values ('1833','1','20/08/2011 00:00');insert into #tmp values ('65','4','27/11/2009 00:00');insert into #tmp values ('42','5','01/09/2009 00:00');insert into #tmp values ('55','5','29/10/2009 00:00');insert into #tmp values ('54','5','15/11/2009 00:00');insert into #tmp values ('162','5','07/07/2011 00:00');insert into #tmp values ('68','7','22/09/2009 00:00');insert into #tmp values ('69','8','15/12/2009 00:00');insert into #tmp values ('64','9','18/11/2009 00:00');insert into #tmp values ('95','9','04/02/2010 00:00');insert into #tmp values ('99','9','08/03/2010 00:00');insert into #tmp values ('2929','9','29/01/2013 00:00');insert into #tmp values ('3','22','21/07/2009 00:00');insert into #tmp values ('7','22','21/07/2009 00:00');insert into #tmp values ('123','68','18/06/2010 00:00');insert into #tmp values ('60','69','05/11/2009 00:00');insert into #tmp values ('40','70','23/03/2010 00:00');insert into #tmp values ('1706','77','25/07/2011 00:00');insert into #tmp values ('706','78','08/12/2010 00:00');insert into #tmp values ('707','78','09/12/2010 00:00');insert into #tmp values ('118','79','05/05/2010 00:00');insert into #tmp values ('410','84','18/10/2010 00:00');insert into #tmp values ('724','84','08/12/2010 00:00');insert into #tmp values ('725','84','09/12/2010 00:00');insert into #tmp values ('2181','84','19/10/2011 00:00');SELECT PLAN_ID FROM( SELECT PLAN_ID, ROW_NUMBER() OVER (PARTITION BY CARE_ID ORDER BY N5_3_PLAN_AGREE_DATE, PLAN_ID) AS RN FROM #tmp) s WHERE RN = 1;DROP TABLE #tmp; RESULTS PLAN_ID18336542686964312360401706706118410 BTW, when you post your question if you can include DDL statements for creating sample data like I have here, that makes it easier for someone to respond. So you will get more accurate and faster responses. |