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 |
|
Humate
Posting Yak Master
101 Posts |
Posted - 2007-12-11 : 11:44:25
|
| Hi All,I want a query to identify rows with the most recent entry for each Unique reference.My table contains three main fields:Reference--------------Date---------------Action1234------------10/12/2007 15:00---------Updated1234------------10/12/2007 17:00---------Deleted1235------------10/12/2007 16:23---------Updated 1235------------10/12/2007 16:29---------UpdatedIn this scenario I would want the query to return:1234------------10/12/2007 17:00---------Deleted1235------------10/12/2007 16:29---------UpdatedIn the table there could be many actions on the same reference number, I just want to return 1 row for each reference number showing the date and most recent Action.Can anyone help - I feel like this is so annoyingly simple!Thanks in advanceHumate |
|
|
mfemenel
Professor Frink
1421 Posts |
Posted - 2007-12-11 : 11:57:52
|
| Something like this would work for you.select base.reference,base.mydate,tablename.actionfrom( select reference,max(date) as mydate, from tablename group by reference)baseinner join tablename on base.[date]=tablename.[date] and base.reference=tablename.referenceMike"oh, that monkey is going to pay" |
 |
|
|
Humate
Posting Yak Master
101 Posts |
Posted - 2007-12-11 : 15:02:38
|
| hmm... I get an error near 'from' when trying to use that code.Select REF,dateref,OutcomeFrom (select ref, max(dateref), from table1 group by ref) as baseInner Join table1 on base.[dateref]=[table1].[dateref] and base.ref=[table1].refIs that how you meant? |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-12-11 : 15:15:15
|
SELECT Reference, Date, ActionFROM (SELECT Reference, Date, Action, ROW_NUMBER() OVER (PARTITION BY Reference ORDER BY Date DESC) AS RecID) AS dWHERE RecID = 1ORDER BY Reference E 12°55'05.25"N 56°04'39.16" |
 |
|
|
Humate
Posting Yak Master
101 Posts |
Posted - 2007-12-11 : 16:53:04
|
| I solved the above problem and used the example from mfemenel, which works great, many thanks!Peso - I will try your method too, looks interesting. |
 |
|
|
|
|
|
|
|