Gopal
Gopal

Reputation: 11982

How to delete the last record

Using SQL Server 2000

Table

ID Date Value

001 23-02-2009 300
001 24-02-2009 400
001 25-02-2009 150
002 23-02-2009 300
002 24-02-2009 400
003 23-02-2009 150
.....
.....

From the above table i want to delete the last date for each id.

How to make a query

Expected output

 ID Date Value

    001 23-02-2009 300
    001 24-02-2009 400
    002 23-02-2009 300
    .....
    .....
    .....

Need Query Help

Upvotes: 0

Views: 2835

Answers (1)

rsbarro
rsbarro

Reputation: 27339

You can achieve this by doing a subselect and a join in the DELETE statement. For example:

DECLARE @myTable TABLE(ID VARCHAR(3), [Date] DATETIME, Value INT)
INSERT INTO @myTable VALUES('001', CONVERT(DATETIME, '23-02-2009', 103), 300)
INSERT INTO @myTable VALUES('001', CONVERT(DATETIME, '24-02-2009', 103), 400)
INSERT INTO @myTable VALUES('001', CONVERT(DATETIME, '25-02-2009', 103), 150)
INSERT INTO @myTable VALUES('002', CONVERT(DATETIME, '23-02-2009', 103), 300)
INSERT INTO @myTable VALUES('002', CONVERT(DATETIME, '24-02-2009', 103), 400)
INSERT INTO @myTable VALUES('003', CONVERT(DATETIME, '23-02-2009', 103), 150)

DELETE @myTable
FROM @myTable M
JOIN (SELECT ID, MAX([Date]) as [Date] FROM @myTable GROUP BY [ID]) G
    ON G.ID = M.ID AND G.[Date] = M.[Date]

SELECT * FROM @myTable

Please note that I tested this SQL against SQL Server 2005, but I believe it should work in SQL Server 2000 as well.

Upvotes: 3

Related Questions