Solved

Duplicate records - Select based on latest date

Posted on 2009-04-07
2
302 Views
Last Modified: 2012-05-06
Given the following table:

ID  ItemNo     Datestamp
1   10           2009-03-27 15:58:18.000
2   10           2009-03-27 16:07:14.000
3   20           2009-03-27 16:17:15.000
4   30           2009-03-27 16:42:17.000
5   30           2009-03-27 16:33:33.000
6   40           2009-03-27 16:21:46.000
7   50           2009-03-27 16:49:18.000


Notice that the ID is unique (actually in my table it is a guid) and the ItemNo field has some duplicates.  

I would like to query all the fields in this table and select only the records with the latest datestamp - if there are multiple records with the same item number, get only 1 record for that ItemNo and choose the latest datestamp. How would I do that?

I have tried a few different queries using Group By, but have not been completely successful.


Thanks in advance,


Steve
0
Comment
Question by:scooper082898
2 Comments
 
LVL 32

Accepted Solution

by:
bhess1 earned 500 total points
ID: 24091971
A query like this should return the data you are looking for....

SELECT m.*
FROM MyTable m
INNER JOIN (
    SELECT ItemNo,
        MAX(DateStamp) as MaxStamp
    FROM MyTable
    GROUP BY ItemNo
    ) Filter
    ON m.ItemNo = Filter.ItemNo
    AND m.DateStamp = MaxStamp
0
 

Author Closing Comment

by:scooper082898
ID: 31567755
Mch appreciated. I have never used "Filter on" before.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

There are some very powerful Data Management Views (DMV's) introduced with SQL 2005. The two in particular that we are going to discuss are sys.dm_db_index_usage_stats and sys.dm_db_index_operational_stats.   Recently, I was involved in a discu…
INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question