我正在使用带有SQL Server 2008的T-Sql。假设我有父表:
项目:
ProjectID ProjectNam
1 Test Project 1
2 Test Project 2
和子表 ProjectRevisions :
ProjectRevID ProjectID DateCreated 11 1 10/15/2009 12 1 10/19/2009 13 1 10/25/2009 21 2 10/05/2009
如何为每个项目结束最新的ProjectRevision?像这样:
ProjectRevID ProjectID DateCreated 13 1 10/25/2009 21 2 10/05/2009
答案 0 :(得分:3)
select x.mProjectRevID, p.ProjectID, p.ProjectNam, x.mDateCreated
from Projects p
inner join
(
select projectID
, max(ProjectRevID) as mProjectRevID
, max(DateCreated) as mDateCreated
from ProjectRevisions
group by ProjectID
) x
on x.projectID = p.ProjectID
假设ProjectRevID和DateCreated都“朝着同一方向”,即下一个版本获得的ID高于前一个版本。
如果需要,从项目加入允许您从项目中访问其他列。
答案 1 :(得分:3)
无论ProjectRevId和DateCreated之间是否存在任何关系,下面的查询都将有效。
SELECT *
FROM ProjectRevisions
INNER JOIN (
SELECT ProjectId
, MAX(DateCreated) AS DateCreated
FROM ProjectRevisions
GROUP BY ProjectId
) AS CurrentRevision
ON CurrentRevision.ProjectId = ProjectRevisions.ProjectId
AND CurrentRevision.DateCreated = ProjectRevisions.DateCreated
答案 2 :(得分:1)
select ProjectRevID, ProjectID, DateCreated from Projects p inner join ProjectRevisions on ProjectRevisions.ProjectId = p.ProjectId where ProjectRevId = ( select ProjecRevId from ProjectRevisions where ProjectId = p.ProjectId order by DateCreated desc limit 1 )