Please put the following code into Query Analyzer to see what I'm attempting to do...This code is supposed to search through training events (eventid) and return only the most recent row (max dateAttained) for each event. It fails where 2 events have the same dateAttained and eventid. declare @tmp table (historyid int, userid int, eventid int, weighting numeric(5,2), dateAttained datetime)insert into @tmp values (1, 450, 1, 80, '01/01/2001')insert into @tmp values (2, 450, 2, 20, '01/01/2001 14:56:05')insert into @tmp values (3, 450, 1, 80, '01/01/2001')insert into @tmp values (4, 450, 2, 20, '10/01/2001 13:33:25')insert into @tmp values (5, 450, 2, 20, '01/01/2001')insert into @tmp values (1, 520, 1, 80, '01/01/2001')insert into @tmp values (2, 520, 2, 20, '01/01/2001 14:56:05')insert into @tmp values (3, 520, 1, 80, '01/01/2001')insert into @tmp values (4, 520, 2, 20, '10/01/2001 13:33:25')insert into @tmp values (5, 520, 2, 20, '01/01/2001')select * from @tmpselect *from @tmp tmpwhere (userid = 450) and (tmp.dateAttained = (select max(dateAttained) from @tmp tmp2 where tmp.eventid = tmp2.eventid))
You will see 2 sets of results. Some of this data is captured by ASP.NET, hence the accurate datetime, and some is manually entered. The second resultset is supposed to show (for a given user), the most recent training eventid's that they attended, but it doesn't work correctly because 2 (manually entered) events have occurred on the same day. How can I amend the SELECT statement to add the following logic? "For the given userid, if duplicate eventid/dateAttained rows exist, only show the row with the highest historyid?"So the correct results would be...:historyid eventid weighting dateAttained---------------------------------------------------------------4 2 20.00 2001-10-01 13:33:25.0001 1 80.00 2001-01-01 00:00:00.0003 1 80.00 2001-01-01 00:00:00.000---------------------------------------------------------------
The second row is eliminated because it has the same eventid/dateAttained as row below it, and also has the lowest historyid of the two.