Solved

Deleting all records but most recent date

Posted on 2007-03-27
2
260 Views
Last Modified: 2010-03-20
I have a question on MS SQL 2000.  I am trying to put together a query to delete certain records.  The schema is as follows:

[name][date][item1][item2]...

examples being:

[andrew][2/2/07][meat][cheese]
[bob][1/1/07][milk][eggs]
[bob][1/2/07][milk][cheese]

Some names occur only once, but there are multiple occurances of the same names with different values for each field thereafter.

What I want to do is delete all records except for the record with the most recent date (keeping name as the key).  I want to end up with only one entry for each name.  When I type this out it seems simple, but I can't seem to formulate the right query.

Thanks for the help!
0
Comment
Question by:Ant_Dogg
2 Comments
 
LVL 10

Accepted Solution

by:
lahousden earned 50 total points
Comment Utility
delete t
from Your_Table as t
left join (select [name], max ([date]) max_date
             from Your_Table
             group by [name]) as m on m.[name] = t.[name] and m.max_date = t.[date]
where m.[name] is null
0
 
LVL 50

Expert Comment

by:Lowfatspread
Comment Utility
delete from yourtable
 where exists (select name from yourtable as x
                           where yourtable.name = x.name
                                and yourtable.date < x.date)
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

763 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now