I'm currently doing a document management system that I'm having a few problems with. I want to be able to select and show each unique document with the highest version number This is my current code:
SELECT DISTINCT( policyheader.policytitle ),
Max(policyrecords.policyversion) AS maxPolicy,
policyrecords.useruploaddate,
policyrecords.policydesc,
LEFT(policyrecords.whatchanged, 30) AS changes,
policyheader.policyref
FROM policyrecords
INNER JOIN policyheader
ON policyrecords.policyref = policyheader.policyref
GROUP BY policyrecords.policydesc,
policyrecords.policyversion
I have also been trying IN
as well. It is returning this data:
What I want it to return is this data:
You can approach this in several ways. The not exists
method often performs well:
SELECT ph.policyTitle, pr.*
FROM policyrecords pr INNER JOIN
policyheader ph
ON pr.policyRef = ph.policyRef
WHERE not exists (select 1
from policyrecords pr2
where pr2.policyRef = pr.policyRef and
pr2.policyVersion > pr.policyVersion
);
This implements the following logic: "Get me all the records from policyrecords
where there is no records with the same policyRef
and a larger policyVersion
." This is a fancy way of saying get me the maximum version.
Try this query
SELECT
DISTINCT(policyheader.policyTitle),
MAX(policyrecords.policyVersion) AS maxPolicy,
policyrecords.userUploadDate,
policyrecords.policyDesc,
left(policyrecords.whatChanged,30) as changes,
policyheader.policyRef
FROM policyrecords
INNER JOIN policyheader ON policyrecords.policyRef = policyheader.policyRef
GROUP BY
DISTINCT(policyheader.policyTitle)
If you group by version, you will see all the versions for one policyTitle :)
SELECT
policyheader.policyTitle,
policyrecords.policyVersion,
policyrecords.userUploadDate,
policyrecords.policyDesc,
left(policyrecords.whatChanged,30) as changes,
policyheader.policyRef
FROM policyrecords
INNER JOIN policyheader ON policyrecords.policyRef = policyheader.policyRef
GROUP BY
policyrecords.policy
order by policyrecords.policyVersion desc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.