Non è stato divertente leggere la tua domanda, ma penso che il problema sia qui:
LEFT JOIN (
SELECT max(notification_date) notification_date, client_id
FROM og_ratings
WHERE notification_date NOT IN (
SELECT max(notification_date)
FROM og_ratings
)
se vuoi la data massima per ogni cliente devi GROUP BY client_id:
SELECT client_id, max(notification_date) notification_date
FROM og_ratings
GROUP BY client_id
se vuoi il secondo massimo ci sono poche opzioni, sto usando questa che è più facile da capire ma non è necessariamente la più performante:
SELECT client_id, max(notification_date) notification_date
FROM og_ratings
WHERE
(client_id, notification_date) NOT IN (
SELECT client_id, max(notification_date)
FROM og_ratings GROUP BY client_id
)
GROUP BY client_id
terzo problema, stai usando un LEFT JOIN, il che significa che restituirai tutti i valori da og_ratings indipendentemente dal fatto che siano il secondo massimo o meno. Usa INNER JOIN in questo contesto:
SELECT
r.client_id,
c.id,
t.id,
..etc...
FROM
og_ratings r INNER JOIN (
SELECT client_id, max(notification_date) notification_2nd_date
FROM og_ratings
WHERE
(client_id, notification_date) NOT IN (
SELECT client_id, max(notification_date)
FROM og_ratings GROUP BY client_id
)
GROUP BY client_id
) r2
ON r.notification_date = r2.notification_2nd_date
AND r.client_id = r2.client_id
LEFT JOIN og_companies c ON r.client_id = c.id
LEFT JOIN og_rating_types t ON r.rating_type_id = t.id
LEFT JOIN og_actions a ON r.pacra_action = a.id
LEFT JOIN og_outlooks o ON r.pacra_outlook = o.id
LEFT JOIN og_lterms l ON r.pacra_lterm = l.id
LEFT JOIN og_sterms s ON r.pacra_sterm = s.id
LEFT JOIN pacra_client_opinion_relations pr ON pr.opinion_id = c.id
LEFT JOIN pacra_clients pc ON pc.id = pr.client_id
LEFT JOIN city ON city.id = pc.head_office_id
WHERE
r.client_id IN (
SELECT opinion_id FROM pacra_client_opinion_relations
WHERE client_id = 50
)