Solved

Deleting all records but most recent date

Posted on 2007-03-27
2
265 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
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
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
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

861 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