在下面的查询中,我使用GROUP BY
子句获取最近更新的记录列表取决于更新日期。但是由于某些内部原因,我希望在没有GROUP BY
子句的情况下进行查询。可以请任何人帮我解决这个问题。
SELECT Proj_UpdatedDate,
Proj_UpdatedBy
FROM ProjectProgress PP
WHERE Proj_UpdatedDate IN (SELECT MAX(Proj_UpdatedDate)
FROM ProjectProgress
GROUP BY
Proj_ProjectID)
ORDER BY
Proj_ProjectID
答案 0 :(得分:1)
假设您的意思是MAX(Proj_UpdatedDate),使用TOP 1会给出相同的结果:
SELECT Proj_UpdatedDate,
Proj_UpdatedBy
FROM ProjectProgress PP
WHERE Proj_UpdatedDate IN (SELECT TOP 1 Proj_UpdatedDate
FROM ProjectProgress
ORDER BY Proj_UpdatedDate DESC)
ORDER BY
Proj_ProjectID
但是,您的查询实际上会返回多个日期,因为它是GROUPED BY Proj_ProjectId(每个项目的最大日期)。这是您想要的结果 - 显示项目更新的日期列表以及由谁更新?
如果是这样,请尝试使用ROW_NUMBER():
SELECT Proj_UpdatedDate, Proj_UpdatedBy
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY Proj_ProjectID ORDER BY Proj_UpdatedBy DESC) rn,
Proj_UpdatedDate,
Proj_UpdatedBy
FROM ProjectProgress
) t
WHERE rn = 1
这是SQL Fiddle。这假设您运行的是SQL Server 2005或更高版本。
祝你好运。