开发者

SQL Query - Get Most Recent Revision

I'm using T-Sql with SQL Server 2008. Say I have parent table:

Projects:

ProjectID  ProjectNam
1          Test Project 1
2          Test Project 2

and child table ProjectRevisions:

ProjectRevID ProjectID DateCreated
11           1         10/15/2009
12           1         1开发者_C百科0/19/2009
13           1         10/25/2009
21           2         10/05/2009

How do I end up with the most recent ProjectRevision for each Project? Like this:

ProjectRevID ProjectID DateCreated
13           1         10/25/2009
21           2         10/05/2009


The query below will work regardless of any relationship between ProjectRevId and 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


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

assuming that ProjectRevID and DateCreated are both "going in the same direction" i.e. the next revision receives a higher ID than the previous one.

Joining from Projects allows you to access other columns from Projects, if need be.


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
  )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜