2012-10-06 58 views
1

我有一個SQL查詢,用戶可以在其中創建表單的多個「修訂版」。目前我們將修訂ID傳遞給查詢以檢索值(您可能會猜到),這很好 - 但我想擴展到還選擇以前的修訂行(如果它們是以前的修訂版)。每個修訂版都有一個編號,當它們創建新的修訂版時,它會增加。這裏是我的查詢到目前爲止這似乎並沒有運行(當然值1,值2是我的查詢中的實際列)SQL - 派生表加入

SELECT ID, SageJobID, SageJobPK, DateID, Revision, StatusID, Value1, Value2 
FROM CVRs 
LEFT OUTER JOIN (SELECT TOP(1) * 
        FROM CVRs AS prevCVR 
        WHERE (prevCVR.DateID = CVRs.DateID 
        AND prevCVR.SageJobPK = CVRs.SageJobPK 
        AND prevCVR.ID <> CVRs.ID) 
        ORDER BY prevCVR.Revision DESC) AS 'PrevCVR' 
WHERE  (CVRs.ID = @ID) 

看來我無法訪問主CVR行我選擇從我的加入。有任何想法嗎?

+2

請在提問SQL問題時給RDBMS和版本添加標籤。我假設可能來自'TOP'的SQL Server –

回答

1

我做了一個SQL撥弄一個簡化版本給你出個主意,你如何解決這個問題。 SQL小提琴演示here

這將是那麼這個

SELECT ID, SageJobID, SageJobPK, DateID, Revision, StatusID, Value1, Value2 
FROM CVRs 
WHERE DateId in (select dateid from cvrs where CVRs.ID = @ID) 
    and sagejobpk in (select sagejobpk from cvrs where CVRs.ID = @ID) 
order by revision desc 

編輯:我又SQL Fiddle也採取了DateId方面的,但我有一個問題:是不是所有的CV的修訂屬於一起必須是相同的DateIdSageJobPK

0

看起來你需要OUTER APPLY而不是OUTER JOIN

SELECT CVRs.*, 
     PrevCVR.* /*TODO: Select desired columns*/ 
FROM CVRs 
     OUTER APPLY (SELECT TOP(1) * 
        FROM CVRs AS prevCVR 
        WHERE (prevCVR.DateID = CVRs.DateID 
          AND prevCVR.SageJobPK = CVRs.SageJobPK 
          AND prevCVR.ID <> CVRs.ID) 
        ORDER BY prevCVR.Revision DESC) AS PrevCVR 
WHERE (CVRs.ID = @ID) 
0
SELECT a.ID, a.SageJobID, a.SageJobPK, a.DateID, a.Revision, a.StatusID, a.Value1, a.Value2 
FROM CVRs as a 
LEFT OUTER JOIN CVRs as b 
on .DateID = b.DateID AND a.SageJobPK = b.SageJobPK AND a.ID <> b.ID 
where a.ID = @ID ORDER BY b.Revision DESC 
0

我認爲最簡單的方式來獲得最新的多個版本使用排序功能:

select SageJobID, SageJobPK, DateID, Revision, StatusID, Value1, Value2 
from (select CVR.*, 
      row_number() over (partition by id order by revision desc) as seqnum 
     from CVRs 
    ) c 
where c.ID = @ID and seqnum <= 2 
order by revision desc 

SEQNUM訂單的修改,通過指定1到最新,2到第二最近的,所以上。