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 |
Gerdis
Starting Member
1 Post |
Posted - 2013-07-30 : 06:25:36
|
I have a table with duplicated records (well technically they all are disitnct records with some variations) and I need to select the only record which has latest DATETIMEACHIVED value. How do I do this?System_ID | PARCEL_ID | Wheight | DATETIMEACHIVED----------------------------------------------------1 | 1 | 0.5 | 01-01-20121 | 1 | 0.25 | 02-01-20121 | 1 | 0.51 | 03-01-20121 | 1 | 0.26 | 05-01-20121 | 1 | 0.56 | 04-01-20121 | 1 | 0.25 | 06-01-20121 | 8 | 1.36 | 13-02-20101 | 8 | 1.36 | 14-02-20102 | 1 | 30.15 | 29-06-20132 | 1 | 28 | 29-07-20132 | 1 | 21 | 29-08-2013If selected correctly I would have a result System_ID | PARCEL_ID | Wheight | DATETIMEACHIVED------------------------------------------------------1 | 1 | 0.25 | 06-01-20121 | 8 | 1.36 | 14-02-20102 | 1 | 21 | 29-08-2013Anyones help on this would be greatly appreciated |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-07-30 : 06:29:43
|
[code]SELECT System_ID, Parcel_ID, Wheight, DATETIMEACHIVEDFROM( SELECT System_ID, Parcel_ID, Wheight, DATETIMEACHIVED, ROW_NUMBER() OVER(PARTITION BY System_ID, PARCEL_ID ORDER BY DATETIMEACHIVED DESC) AS RN FROM YourTable) sWHERE RN = 1;[/code]If you can have duplicates, i.e., more than one row for a given combination of System_ID and Parcel_ID with the same max date, and if you want to get all such duplicates, use RANK() instead of ROW_NUMBER() |
|
|
|
|
|