I have this Query were i only want the employees on the most recent RunID and WHERE they are over 25. As you can see from my results it is returning the employees who are over 25 and THEIR most recent RunID. I only want employees from the last RunID(2131). Next week the RunID will be (2132) and it will be going up every week. Is there a way to only get the employees on the last RunID? Really stuck on this one. Here is a picture from my Query.
SELECT DISTINCT
ed.EeID,
CONCAT(ed.Forename, '', ed.Surname) AS 'Name',
MAX(pr.RunID)
FROM EeDetails ed
INNER JOIN EeRunBals erb on erb.EeID = ed.EeID
INNER JOIN PayrollRuns pr on pr.RunID = erb.RunID
WHERE ed.BirthDate < '1994-01-01'
--WHERE pr.RunID = MAX(pr.RunID)
GROUP BY ed.EeID, ed.Forename, ed.Surname, ed.BirthDate
ORDER BY ed.EeId
You can use a having clause to filter an aggregated value i.e. max runid. Also you need to use subquery to get the max runid because in the parent query the MAX(pr.RunID)
is actually max runid of an employee(grouped by) rather than all employees. In your code, you can use the query like this:
SELECT DISTINCT
ed.EeID,
CONCAT(ed.Forename, '', ed.Surname) AS 'Name',
MAX(pr.RunID)
FROM EeDetails ed
INNER JOIN EeRunBals erb on erb.EeID = ed.EeID
INNER JOIN PayrollRuns pr on pr.RunID = erb.RunID
WHERE ed.BirthDate < '1994-01-01'
GROUP BY ed.EeID, ed.Forename, ed.Surname, ed.BirthDate
HAVING MAX(pr.RunID)=(select MAX(RunID) from PayrollRuns)
ORDER BY ed.EeId
Hope this helps.