1

我有一个DocumentHistory包含这些列的表:

HistoryId   DocumentId    ChangeDate
    1           100       1/1/2005  
    2           100       2/1/2010         
    3           200       2/2/2006 
    4           100       2/2/2001 
    5           200       2/2/2000

HistoryId是关键。我想编写一个TSQL查询,找到ChangeDate每个文档的最大值并返回它HistoryId,我的意思是查询结果将是:

HistoryId       ChangeDate
    2            2/1/2010
    3            2/2/2006

我该怎么做?

4

2 回答 2

2

使用排名功能 ROW_NUMBER() OVER(PARTITION BY ... ORDER BY...)

WITH CTE
AS
(
   SELECT *, 
     ROW_NUMBER() OVER(PARTITION BY DocumentId 
                       ORDER BY ChangeDate DESC) AS RN
   FROM DocumentHistory 
)
SELECT HistoryId, ChangeDate
FROM CTE
WHERE RN = 1;

在这里查看它的实际效果:

于 2013-07-10T09:17:53.693 回答
2
SELECT b.HistoryId,a.ChangeDate from 
(SELECT DocumentId,max( ChangeDate) as ChangeDate
FROM DocumentHistory   GROUP BY DocumentId) a
INNER JOIN DocumentHistory b ON a.DocumentId=b.DocumentId AND a.ChangeDate=b.ChangeDate

这将适用于没有 CTE 支持 测试的数据库http://www.sqlfiddle.com/#!3/c33be/16

于 2013-07-10T09:32:15.830 回答