2013-07-10 96 views
1

我有一個DocumentHistory表與此列:TSQL的GroupBy最大

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 

我該怎麼辦呢?

+1

這有助於[公用表表達式(http://msdn.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) –

回答

2

使用ranking functionROW_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; 

看到它在這裏的行動:

+0

@MahmoodGamal:謝謝,是否有可能使用這個查詢作爲視圖? – Masoud

+0

@Masoud - 當然,只要'CREATE VIEW viewname as'然後放置查詢,看到這個[** Demo **](http://www.sqlfiddle.com/#!3/0ebf6/1)。 –

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