I have a system that contains two tables. A "projects" table, and an "additions" table. The projects table contains original data for a "project". The details on the project cannot be changed directly. Instead an "addition" is used if any details need to change. This way the original entry in projects is maintained and as additions are added all the changes can be tracked in order.
One of the project fields is "projectEndDate" which contains the end date of the project. This can be overriden with an addition with "additionEndDate". Additions also contains "additionDateEntered" which logs when the addition was actually entered into the system.
I need to be able to grab all the projects while left joining the additions that contain a new endDate ordered by the newest "additionDateEntered" and getting the "additionEndDate" for that entry. And to finalize, the entire results should be ordered by the "realClosingDate" which is an alias of the newest end date. Usually I can work through these queries but I seem to be really struggling with this one.
Here's what I have so far
SELECT
*,
`additionEndDate`,
GREATEST(COALESCE(`projectEndDate`, 0),
COALESCE(`additionEndDate`, 0)) AS `realEndDate`
FROM
(SELECT
*
FROM
`projects`
WHERE
`projectStatus` = ‘Active’) AS A
LEFT JOIN
(SELECT
*
FROM
`additions`
WHERE
`additionEndDate` IS NOT NULL
GROUP BY `projects_projectId`
ORDER BY `additionEnteredDate` DESC) AS B ON A.projectId = B.projects_projectId
ORDER BY `realEndDate`
The result does not get the latest additionEnteredDate but instead seems to get the first entry in additions only.
EDIT: Here is a sample project and 4 sample additions tied to that project
The query above results in realClosingDate
of 2020-02-12 however the require result should be 2020-02-22 as that is the latest entered addition but not necessarily the MAX() of additionEndDate