2009-11-24 68 views
3

我使用T-SQL與SQL Server 2008中說,我有父表: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

哪個SQL您使用的方言? – pmarflee 2009-11-24 21:11:43

+0

T-SQL與SQL Server 2008 – 2009-11-24 21:12:04

+0

嚴格來說,要獲得顯示的結果並不需要這兩個表。它只需要ProjectRevisions。 – 2009-11-24 21:19:25

回答

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

完美地工作。 +1,謝謝! – 2009-11-24 21:20:04

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。

如果需要,從項目連接允許您訪問項目中的其他列。

+0

在我的實際數據庫中,ProjectRevID是一個GUID,所以MAX(ProjectRevID)沒有意義。感謝您的幫助,但是, – 2009-11-24 21:19:28

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 
)