1

我有一个表的 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 行。有任何想法吗?

4

4 回答 4

1

我制作了一个带有简化版本的 SQL Fiddle,让您了解如何解决它。SQL Fiddle 演示在这里

那将是关于这个

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

于 2012-10-06T13:14:53.333 回答
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 ) 
于 2012-10-06T12:52:14.653 回答
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
于 2012-10-06T12:56:08.327 回答
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 分配给第二最近的,依此类推。

于 2012-10-06T16:29:03.283 回答