我有一个表的SQL查询,用户可以在其中创建表单的多个“修订版”。目前我们将修订的ID传递给查询以检索值(正如您可能猜到的那样),这很好 - 但我想扩展为也选择以前的修订行(如果它们是以前的修订版)。每个修订版都有一个在创建新修订版时递增的编号。这是我到目前为止的查询似乎没有运行(显然值1,值2是我的查询中的实际列)
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行。有什么想法吗?
答案 0 :(得分:1)
我制作了一个带有简化版本的SQL Fiddle,让您了解如何解决它。 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
方面,但我得到一个问题:是否所有归属于一起的简历修订都必须相同DateId
和SageJobPK
?
答案 1 :(得分: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 )
答案 2 :(得分: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
答案 3 :(得分: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通过将最新的,最新的2分配给最近的第二个等来命令修订,依此类推。