Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Annee
Starting Member
1 Post |
Posted - 2012-02-06 : 14:42:33
|
| Need help writing a stored procedure that deletes all the records of a given doc-id except the top 2 max versions of that doc-id. Example:Doc-Id Version------- -------doc1 0doc1 1doc2 0doc2 2doc2 3doc3 0doc3 4doc3 5doc3 6so in the above table1)for doc1: Should not delete anything since only 2 versions exist2)for doc2: Should delete record with version : 0 leaving behind the 2 max versions 2 and 33)for doc3: Should delete records with versions : 0 and 4 leaving behind the 2 max versions 5 and 6Note: The version value for some trans can go as high as 50 or even moreAppreciate any help in developing most optimal query to perform the specified task |
|
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-02-06 : 14:47:18
|
You can use the row-number function to do this - see below. Before you run it, comment the last line, uncomment the line before that and run the query to see the rows that will be deleted. Once you are comfortable, revert the comments and run.;WITH cte AS( SELECT *, ROW_NUMBER() OVER (PARTITION BY [doc-id] ORDER BY [version] DESC) AS RN FROM YourTable)-- SELECT * FROM cte WHERE RN > 2; - uncomment and run this to see what will be deleted.DELETE FROM cte WHERE RN > 2; |
 |
|
|
|
|
|