您可以通過做一個子查詢做到這一點,並在DELETE
語句加入。例如:
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
請注意,我測試了這個SQL對SQL Server 2005,但我相信它也應該在SQL Server 2000中工作。
SQL Server 2000上的[SQL Server ROW_NUMBER()可能重複?](http://stackoverflow.com/questions/4081753/sql-server-row-number-on-sql-server-2000) –