If you say SQL (Structured Query Language), but it really means SQL Server (Microsoft Relational Database System), and if you are using SQL Server 2005 or later, you can use CTE (Common Table Expression) for this purpose.
With this CTE, you can break down your data according to some criteria - i.e. your ItemId (or combination of columns) - and have a SQL Server number for all of your rows, starting with 1 for each of these sections, sorted by some other criteria - that is, probably version (or some other column).
So try something like this:
;WITH PartitionedData AS ( SELECT itemid, fieldid, version, ROW_NUMBER() OVER(PARTITION BY ItemId ORDER BY version DESC) AS 'RowNum' FROM dbo.VersionedFields ) DELETE FROM PartitionedData WHERE RowNum > 1
Basically, you break down your data according to certain criteria and the numbering of each section, starting from 1 for each new section, sorting by other criteria (for example, Date or Version).
Thus, for each “section” of data, the “latest” record has a value of RowNum = 1, and any others that belong to the same section (using the same partitino values) will be sequentially numbered with values from 2 to, however, there are many lines in this section .
If you want to keep only the newest record, delete everything with RowNum greater than 1, and you're done!
marc_s
source share