2013-08-31 260 views
0

我的查詢返回每個用戶標識的最新條目,但我需要它返回每個用戶標識和任務名稱的最新條目。我試圖用group by,但是我得到一個錯誤。有什麼我做錯了嗎?謝謝!SQL Server查詢

SELECT UserId, TaskName, First, Last, email, ValueDate, Analysis 
FROM (SELECT UserId, TaskName, First, Last, 
email, ValueDate, Analysis, 
ROW_NUMBER() OVER(PARTITION BY UserID 
ORDER BY ValueDate DESC) AS rk 
FROM MyTable) AS L 
WHERE rk = 1 

回答

1

此時應更換PARTITION BY用戶IDPARTITION BY用戶ID,任務名稱

SELECT UserId, TaskName, First, Last, email, ValueDate, Analysis 
FROM (SELECT UserId, TaskName, First, Last, 
email, ValueDate, Analysis, 
ROW_NUMBER() OVER(PARTITION BY UserID, TaskName 
ORDER BY ValueDate DESC) AS rk 
FROM MyTable) AS L 
WHERE rk = 1 
0

沒有有一些數據,以測試和表格結構,我只能假設你真的想實現什麼,但它可能是一些看起來像這樣的:

SELECT UserId, TaskName, First, Last, email, max(ValueDate), Analysis 
FROM MyTable 
GROUP BY UserId, TaskName, First, Last, email, Analysis 
ORDER BY MAX(ValueDate) DESC