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.
Author |
Topic |
stamford
Starting Member
47 Posts |
Posted - 2014-03-21 : 13:46:35
|
In the following example table what script would return a single row for each PERSON_ID which has a MAX(PRE_EVENT_DATE) which is <= ACTUAL_EVENT_DATE and if there are two values of PRE_EVENT_DATE the same then the highest value of EVENT_ID is the decider.PERSON_ID EVENT_ID PRE_EVENT_DATE EVENT_TYPE ACTUAL_EVENT_DATE369 902 27/07/2010 00:00 TE 28/07/2010 00:00369 117 28/07/2010 00:00 CH 28/07/2010 00:00481 200 29/07/2010 00:00 CH 07/09/2010 00:00481 12 30/07/2010 00:00 CH 07/09/2010 00:00481 63 31/07/2010 00:00 TE 07/09/2010 00:003213 377 20/01/2012 00:00 TE 20/01/2012 00:003515 789 15/06/2012 00:00 TE 16/09/2013 00:003773 1196 30/01/2013 00:00 CH 10/02/2013 00:004730 1262 22/11/2012 00:00 CH 30/11/2012 00:004863 1322 22/11/2012 00:00 CH 11/12/2012 00:004930 1330 21/11/2012 00:00 CH 11/12/2012 00:004961 1335 22/11/2012 00:00 CH 11/12/2012 00:004961 1333 22/11/2012 00:00 CH 11/12/2012 00:004961 1201 22/11/2012 00:00 CH 11/12/2012 00:005798 1549 02/11/2013 00:00 CH 04/11/2013 00:005870 1561 11/12/2013 00:00 CH 11/12/2013 00:006460 1699 05/01/2014 00:00 CH 10/01/2014 00:00 |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2014-03-21 : 14:09:06
|
Something along these lines, which uses row_number functionSELECT * FROM(SELECT *,ROW_NUMBER() OVER (PARTITION BY PERSON_ID ORDER BY PRE_EVENT_DATE DESC, EVENT_ID DESC) AS RNFROM YourTableWHERE PRE_EVENT_DATE <= ACTUAL_EVENT_DATE )s WHERE RN=1; |
|
|
|
|
|