Solved

Deleting all records but most recent date

Posted on 2007-03-27
2
269 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 10

Accepted Solution

by:
lahousden earned 50 total points
ID: 18803708
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
ID: 18805748
delete from yourtable
 where exists (select name from yourtable as x
                           where yourtable.name = x.name
                                and yourtable.date < x.date)
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

724 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