SQL Server over query

时间:2013-08-31 04:16:52

标签: sql-server

我的查询返回每个用户标识的最新条目,但我需要它返回每个用户标识和任务名称的最新条目。我试图使用group by,但是我收到了一个错误。有什么我做错了吗?谢谢!

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

2 个答案:

答案 0 :(得分:1)

您应该将 PARTITION BY UserID 替换为 PARTITION BY UserID,TaskName

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

答案 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