I have a SQL query for a table in which the user can create multiple ‘revisions’ of a form. Currently we pass in the ID of the revision into the query to retrieve the values (as you can probably guess), which is fine – however I want to extend to also select the previous revisions rows (if they is a previous revision). Each revision has a number which is incremented when they create a new revision. Here’s my query so far which doesn’t seem to run (obviously the value 1,value 2 are the actual columns in my query)
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)
It seems I can’t access the main CVR row I’m selecting from my join. Any ideas?
I made an SQL Fiddle with a simplified version to give you an idea how you can solve it. SQL Fiddle Demo here
That would be then about this
Edit: I made another SQL Fiddle to also take the
DateIdaspect in but I got a question: Is it that all CV revisions that belong together must be of sameDateIdandSageJobPK?