1

我有几个版本分配给 DocumentID。

DocID  Version
ABC    1
ABC    2
ABC    3
DEF    1
DEF    2

如何删除旧版本并仅保留最新版本?删除后,这应该保留在表中:

DocID  Version
ABC    3
DEF    2
4

1 回答 1

6

SQL Server 2005+:

;WITH x AS (SELECT DocID, Version, rn = ROW_NUMBER() OVER 
  (PARTITION BY DocID ORDER BY Version DESC)
  FROM dbo.tablename
)
DELETE x WHERE rn > 1;

对于 SQL Server 2000,它稍微复杂一些。(包含版本信息总是有用的。)

DELETE t
FROM dbo.tablename AS t
LEFT OUTER JOIN 
(
  SELECT DocID, Version = MAX(Version)
  FROM dbo.tablename
  GROUP BY DocID
) AS t2
ON t.DocID = t2.DocID
AND t.Version = t2.Version
WHERE t2.DocID IS NULL;

显然,后一个查询也可以在 MySQL 中工作(感谢@bluefeet)。

对于 MySQL,您是一个人,您最好发布一个完全不同的问题。

于 2012-09-12T13:57:54.803 回答