选择表中每行的最新修订版

时间:2009-09-16 09:34:27

标签: sql sql-server max

我的表结构包含id&组合的主键。两者都是整数的修订。

我需要一个返回每行最新修订版的查询。如果我正确理解this answer,那么以下内容将适用于Oracle DB。

SELECT Id, Title
FROM ( SELECT Id, Revision, MAX(Revision) OVER (PARTITION BY Id) LatestRevision FROM Task )
WHERE Revision = LatestRevision

我使用的是SQL Server(2005),需要一个高性能的查询才能做到这一点。

5 个答案:

答案 0 :(得分:2)

请参阅ayende的this帖子,以评估最佳策略。

答案 1 :(得分:2)

我认为这应该有效(我没有测试过)......

SELECT      ID, 
            Title
FROM        Task AS T
INNER JOIN
(
    SELECT          ID, 
                    Max(Revision)
    FROM            Task
    GROUP BY        ID
) AS sub
ON          T.ID = sub.ID
AND         T.Revision = sub.Revision

答案 2 :(得分:1)

我会尝试创建这样的子查询:

SELECT Id,Title FROM Task T,(按ID选择ID,Max(Revision)MaxRev from Task group)LatestT WHERE T.Revision = LatestT.MaxRev和T.ID = LatestT.ID

另一种选择是“欺骗”并创建一个触发器,如果​​添加了一个项目,则会将修订标记为最新修订。然后将该字段添加到索引中。 (我会将表格链接到仅插入)

也是ID的索引,版本desc可以帮助提高性能

答案 3 :(得分:0)

您发布的查询将在SQL 2005中工作(在兼容模式90下),并且纠正了语法错误:

SELECT t1.Id, t1.Title
FROM ( SELECT Id, Revision, MAX(Revision) OVER (PARTITION BY Id) LatestRevision FROM Task ) AS x
JOIN Task as t1
ON   t1.Revision = x.LatestRevision
AND  t1.id       = x.id

答案 4 :(得分:0)

试试这个:

DECLARE @YourTable table(RowID int, Revision int, Title varchar(10))
INSERT INTO @YourTable VALUES (1,1,'A')
INSERT INTO @YourTable VALUES (2,1,'B')
INSERT INTO @YourTable VALUES (2,2,'BB')
INSERT INTO @YourTable VALUES (3,1,'C')
INSERT INTO @YourTable VALUES (4,1,'D')
INSERT INTO @YourTable VALUES (1,2,'AA')
INSERT INTO @YourTable VALUES (2,3,'BBB')
INSERT INTO @YourTable VALUES (5,1,'E')
INSERT INTO @YourTable VALUES (5,2,'EE')
INSERT INTO @YourTable VALUES (4,2,'DD')
INSERT INTO @YourTable VALUES (4,3,'DDD')
INSERT INTO @YourTable VALUES (6,1,'F')

;WITH YourTableRank AS
(
SELECT
    RowID,Revision,Title, ROW_NUMBER() OVER(PARTITION BY RowID ORDER BY RowID,Revision DESC) AS Rank
    FROM @YourTable
)
SELECT
    RowID, Revision, Title
    FROM YourTableRank
    WHERE Rank=1

输出:

RowID       Revision    Title
----------- ----------- ----------
1           2           AA
2           3           BBB
3           1           C
4           3           DDD
5           2           EE
6           1           F

(6 row(s) affected)