?
Solved

Duplicate records - Select based on latest date

Posted on 2009-04-07
2
Medium Priority
?
330 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:
Brendt Hess earned 2000 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

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

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

I am showing a way to read/import the excel data in table using SQL server 2005... Suppose there is an Excel file "Book1" at location "C:\temp" with column "First Name" and "Last Name". Now to import this Excel data into the table, we will use…
So every once in a while at work I am asked to export data from one table and insert it into another on a different server.  I hate doing this.  There's so many different tables and data types.  Some column data needs quoted and some doesn't.  What …
Screencast - Getting to Know the Pipeline
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…

839 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